当指令从工厂函数调用标记时,在指令模板中进行绑定

时间:2018-09-27 00:23:42

标签: angularjs factory directive

我试图通过这样的指令调用工厂函数:

var app = angular.module('plunker', []);

app.controller('Ctrl', function($scope, peopleFactory) {

  $scope.people = ['john', 'sam', 'roy'];

  $scope.test = function(name) {
    var person = peopleFactory.person(name);
    return person;
  }
});

app.factory('peopleFactory', function() {
  var factory = {};

  factory.person = function(name) {
    var people = {
      john: {
        firstName: "John",
        lastName: "Smith",
        id: 123,
        tag: "<div id='{{person.id}}'>{{person.firstName}} is a doctor and his id is {{person.id}}</div>" +
          "<h1>{{person.lastName}}</h1>"
      },
      sam: {
        firstName: "Sam",
        lastName: "Cole",
        id: 456,
        tag: "<div>{{person.firstName}} has a different text</div>" +
          "<h1>{{person.lastName}}</h1>"
      },
      roy: {
        firstName: "Will",
        lastName: "Kan",
        id: 789,
        tag: "<h4>Some text about this person named {{person.firstName}} {{person.lastName}}</h4>"
      }
    };

    return people[name];
  };


  return factory;
})
app.directive('changeIt', function($compile) {
  return {
    restrict: 'CA',
    scope: {
      getDataFn: '&'
    },
    template: '{{getDataFn().tag}}'
  }
});
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js" data-semver="1.0.7"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="Ctrl">
  <ul>
    <li data-ng-repeat="person in people">
      <div class="change-it" get-data-fn="test(person)"></div>
    </li>
  </ul>
</body>

</html>

我知道那里缺少某些内容,这就是为什么我无法在tag键中绑定person.firstName等等的原因。有人能指出我正确的方向,我该如何纠正?这是小矮人:

http://plnkr.co/edit/dQknKe0wRRgTGnPYQ3Ta?p=preview

0 个答案:

没有答案