在用函数作为模板的重复AngularJS指令中访问' $scope '

Access `$scope` in Repeating AngularJS Directive with Function as Template

本文关键字:指令 访问 scope AngularJS 函数      更新时间:2023-09-26

我怎么能访问一个对象从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 ?

我认为你必须修改你的方法。无法从模板函数访问作用域。您可以在模板本身中使用ng-if,而不是在模板函数中使用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>'
     }
  });

  <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'});
  });

演示活塞在这里