在自定义指令中获取$ parent。$ index

时间:2016-07-02 12:35:24

标签: angularjs angularjs-directive angularjs-scope

<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>

在上面的代码中,我无法访问自定义指令中的父ng-repeat索引。我可以获得父ng-repeat的索引

1 个答案:

答案 0 :(得分:0)

  

此示例可以帮助您弄清楚如何在指令中获取索引等等。

&#13;
&#13;
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)
                }
            }
        })
&#13;
<!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>
&#13;
&#13;
&#13;