如何将变量注入子指令

时间:2013-06-05 20:57:59

标签: javascript angularjs angularjs-directive

对于以下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: '=' }
 });

这一点html:

<div my-directive></div>

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

1 个答案:

答案 0 :(得分: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>'

演示: Here is a fiddle