$index的ngRepeat里面angularjs指令

前端之家收集整理的这篇文章主要介绍了$index的ngRepeat里面angularjs指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图找到最好的方法来获得一个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

我很难理解这句话告诉我什么。所以,我试图做的是这…

首先,ngRepeat指令与我的指令一起使用在“testTemplate”中:

<ul>
   <li my-attr="test()" my-directive ng-repeat="value in values" class="span2">
   </li>
</ul>

接下来,我的指令定义:

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

现在终于,我试图定义的控制器内的“测试”函数为引用指令的父模板。

function TestTemplateCtrl($scope,testTemplate) {
    $scope.test = function() {
        alert('in test');
        $scope.count = "1";
    }
}

所以第一个问题是我的“测试”函数在父中没有被执行。也许我不明白如何应该调用父控制器中的测试函数。现在我实际上还没有增加,但是是上面的正确的方式,我会去增加我的计数,当我到达那一点,如果我可以得到测试功能开火?

而不是scope。$ parent。$ index你可以考虑传递$ index作为指令属性
<li my-directive index="{{$index}}" ng-repeat="value in values">

指示:

myApp.directive('myDirective',function() {
    return {
        replace: true,// transclude: true,scope: {
            index: '@'
        },template: '<div>testing {{index}}</div>',link: function(scope,attrs) {
            // ...
        }
    }
});

Fiddle

原文链接:https://www.f2er.com/angularjs/145583.html

猜你在找的Angularjs相关文章