使用函数作为模板重复AngularJS指令访问`$ scope`

时间:2014-07-02 00:17:57

标签: javascript angularjs angularjs-directive angularjs-ng-repeat

当指令使用函数作为模板时,如何从ng-repeat访问传递给指令的对象?

我在指令中设置了以下ng-repeat

<my-directive ng-repeat="item in list.contents" item="item"></my-directive>

app.directive('myDirective', function () {
  return {
    restrict: 'E',
    scope: {
      item: '='
    },
    template: function (element, attrs) {
      // pseudo-code
      if (item.type == "typeA")
        return '<li>{{ item }} one type</li>';
      else
        return '<li>{{ item }} another type</li>';
    }
  };
});

在模板中,{{ item }}工作正常,但我无法弄清楚如何引用item作为ng-repeat传入的对象。使用attrs我可以从标记中获取值,但该值只是一个字符串。

我可以将type作为对象传递给ng-repeat吗?

1 个答案:

答案 0 :(得分:1)

我认为你必须修改你的方法。无法从模板功能访问范围。您可以在模板本身中使用if,而不是在模板函数中使用ng-if语句。

例如:

<强>指令

  app.directive('myDirective',function() { 
     return {
        restrict: 'E',
        scope: { item: '='},
        template: '<div ng-if="item.type==\'one\'">' + 
                      '{{item.name}}' + 
                  '</div>' + 
                  '<div ng-if="item.type==\'two\'">' +
                      '{{item.name}}' + 
                  '</div>'
     }
  });

<强> HTML

  <body ng-app="app" ng-controller='ctrl'> 
       <my-directive ng-repeat="item in items" item="item"></my-directive>
  </body>

<强>控制器

  app.controller('ctrl', function($scope) {
       $scope.items = [];
       $scope.items.push({type:'one', name: 'One'});
       $scope.items.push({type:'two', name: 'Two'});
  });

Demo Plunker Here