Getting $parent.$index inside a custom directive

。_饼干妹妹 提交于 2020-01-10 06:14:26

问题


<li ng-repeat="value in array1 track by $index">
<div ng-repeat="j in array2">
        <div example-directive >
                <p>     {{$index}} ,{{$parent.$index}}</p>
        </div>
</div>
</li>

In the above code I couldnt access parent ng-repeat index inside my custom directive.how can I get the index of parent ng-repeat


回答1:


This sample can helps you to figure out how can get index or etc ... in directives.

var app = angular.module("app", []);

        app.controller("controller", function ($scope) {

            $scope.array1 = [
                {id: "1-1"},
                {id: "1-2"}
            ];

            $scope.array2 = [
                {id: "2-1"},
                {id: "2-2"}
            ];

        });

        app.directive("exampleDirective", function () {
            return {
                restrict: "A",
                scope: {
                    exampleDirective: "="
                },
                link: function (scope, element, attr, ngModel) {
                    console.log(scope.exampleDirective)
                }
            }
        })
<!DOCTYPE html>
<html ng-app="app" ng-controller="controller as ctrl">
<head>
    <title></title>
</head>
<body>

    <ul>
        <li ng-repeat="value in array1 track by $index">
            {{value.id}}
            <ul>
                <li ng-repeat="j in array2">
                    <div example-directive="{parentIndex: $parent.$index, childIndex: $index}">
                        {{j.id}}
                        <p>array1 index: {{$parent.$index}}</p>
                        <p>array2 index: {{$index}}</p>
                    </div>
                </li>
            </ul>
        </li>
    </ul>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

</body>
</html>


来源:https://stackoverflow.com/questions/38160209/getting-parent-index-inside-a-custom-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!