$index of ngRepeat inside angularjs directive
我正试图找到在与自定义指令一起使用的ngrepeat中获取索引位置的最佳方法。我要解决的问题是,对于NGrepeat的每个迭代,我希望知道我在迭代中的位置,这样我就可以基于该索引位置创建自定义模板。
除非有更好的方法来实现这一点,否则我将尝试基于来自指令的文档来实现这一功能:
& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).
http://docs.angularjs.org/guide/directive/指令
我很难理解这句话到底是怎么说的。所以,我想做的是…
首先,"testmlate"中的ngrepeat指令与我的指令一起使用:
1 2 3 4 5 6 7 8 | <ul> <li my-attr="test()" my-directive ng-repeat="value in values" class="span2"> </li> </ul> |
接下来,我的指令定义了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | angular.module('myModule', []) .directive('myDirective', function() { return { replace : true, transclude : true, scope : { test: '&myAttr' }, templateUrl: 'partials/myTemplate.html', link : function(scope, element, attrs) { alert(scope.count); } } }); |
最后,我尝试在控制器中为引用该指令的父模板定义"test"函数。
1 2 3 4 5 6 | function TestTemplateCtrl($scope, testTemplate) { $scope.test = function() { alert('in test'); $scope.count ="1"; } } |
所以第一个问题是我在父系统中的"测试"功能根本没有被执行。也许我不理解应该如何调用父控制器中的测试函数。现在我也没有实际增加,但是上面的方法是正确的吗,当我达到那个点的时候,如果我能启动测试函数,我会增加我的计数吗?
您可以考虑将$index作为一个指令属性传递,而不是使用
1 | <li my-directive index="{{$index}}" ng-repeat="value in values"> |
指令:
1 2 3 4 5 6 7 8 9 10 11 12 13 | myApp.directive('myDirective', function() { return { replace: true, // transclude: true, scope: { index: '@' }, template: 'testing {{index}}', link: function(scope, element, attrs) { // ... } } }); |
小提琴。
正如您指出的,您可以使用$index获取索引。
因为您的测试函数没有被触发,所以您没有执行它。在指令的链接函数中,需要如下内容:
1 | scope.$eval(attrs.myAttr); |