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

标签 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时,我可以将它作为对象获取吗?

最佳答案

我认为你必须改变你的方法。无法从模板函数访问范围。您可以在模板本身中使用 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>'
     }
  });

HTML

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

Controller

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

Demo Plunker Here

关于javascript - 使用函数作为模板重复 AngularJS 指令中访问 `$scope`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24521080/

相关文章:

javascript - javascript中字母递增

javascript - 如何使用angularjs显示文件上传的进度条

angularjs - 如何使用 Protractor ElementArrayFinder 避免 'Index out of Bound' 异常

angularjs - ng-model 不适用于 select 指令

javascript - 使用函数绑定(bind)将值从一个指令传递到另一个指令 '&'

javascript - 如何将查询响应分配给 global.arrays,而不是 global.arrays 数组中的值?

javascript - html 表中removeclass() 的转换

javascript - 如何为 jquery 对话框应用自定义主题?

javascript - 使用矩以编程方式设置 ionic /Angular 日期输入

javascript - AngularJS DOM 选择器