问题描述:

I want my directive to respond on a DOM element click event, the directive would call a service which returns a string and then through the template, (company details property on the scope return the string along with the template html.

At the moment, the template is not showing on screen,

Directive

/// <reference path="../../Scripts/jquery-2.0.3.js" />

myAppModule.directive("displayCompanyDetails", function () {

return {

restrict: "E",

template: "<div id='companyDetails' ng-model='companyDetails'></div>",

link: function (scope, element, attrs) {

$('.companyName').bind('click', function (event) {

scope.companyDetails = scope.GetCompanyDetails(this.id)

});

}

}

});

View

 @foreach (var company in Model)

{

<div>

@Html.Label(company.Name, new { @class = "companyName", id = company.Company_Id })

<p></p>

</div>

}

</div>

<div id="companyDetailsDiv" ng-controller="CompanyDetailsCtrl">

<display-company-details />

</div>

getCompanyDetails service method

GetCompanyDetails: function (customerId)

{

$http.get("http://localhost:61503/Company/CompanyDetails/" +

customerId).success(function (data)

{

}).error(function ()

{

alert("an unexpected error has occured")

});

}

网友答案:

This isn't using a directive, but I think this is the type of functionality with a service that you are looking for:

HTML:

<body ng-app="myApp" ng-controller="MyController">

<div ng:repeat="company in companies" id="companyName" ng-click="getCompanyDetails(company.id);">
    <label><em>Name:</em> {{company.name}}</label>
    <label><em>ID:</em> {{company.id}}</label>
</div>

<hr/>

Address: {{details.address}}<p>
Phone: {{details.phone}}

JS:

var myAppModule = angular.module("myApp", []);
myAppModule.controller('MyController', function($scope, companyDetailsService) {

    $scope.companies = [
      { name: 'company ABC', id:1},
      { name: 'company 123', id:2},
      { name: 'company XYZ', id:3},
    ];

    $scope.details = {};
    $scope.getCompanyDetails = function (id) {
      $scope.details = companyDetailsService.GetCompanyDetails(id);
    };
});

myAppModule.factory("companyDetailsService", function () {

  return { 
    GetCompanyDetails: function(id) {
      var companies = {
        1: {address:"ABC main", phone:"6785309"},
        2: {address:"123 main", phone:"1234567"},
        3: {address:"XYZ main", phone:"9876543"}
      };
      return companies[id];
    }
  };
});

Full Plunk here.

You may also want to take a look at UI-Router and this quick tutorial to get the kind of functionality you are looking for.

相关阅读:
Top