如何将变量注入子指令

问题描述 投票:2回答:1

对于以下angularjs指令:

app = angular.module('ngApp');

app.value('objects', [
  {id: 1, name: 'Jane Doe', active: true},
  {id: 2, name: 'Test Biz', active: false},
  {id: 3, name: 'Another Business', active: false}
]);

app.directive('myDirective', function (objects) {
     return {
       template: '<ul></ul>',
       replace: true,
       compile: function(element, attrs) {
          for(var i=0;i<objects.length;i++) {
            element.append('<div other-directive object={{object}}></div>');
         }
       }
    };
})
.directive('otherDirecctive', function() {
   return {
     template: '<li>{{object.name}}',
     replace: true,
     scope: { object: '=' }
 });

还有这段HT​​ML:

<div my-directive></div>

如何将每个对象传递给子指令?有没有更好的整体方法来构造此代码?

javascript html angularjs angularjs-directive angularjs-ng-repeat
1个回答
1
投票

我建议仅使用一个指令并在模板中利用ng-repeat

app.directive('myDirective', function (objects) {
     return {
       link: function(scope,element,attrs){
           scope.objects = objects;    
       },
       template: '<ul><li ng-repeat="o in objects">{{o.name}}</li></ul>'
    };
});

但是如果您仍然想使用第二个指令,则可以按原样使用,只需将第一个指令的模板更改为:

'<ul><li ng-repeat="o in objects" other-directive object="o"></li></ul>'

Demo: Here is a fiddle

© www.soinside.com 2019 - 2024. All rights reserved.