【问题标题】:Getting $parent.$index inside a custom directive在自定义指令中获取 $parent.$index
【发布时间】:2016-11-04 17:44:34
【问题描述】:
<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 的索引

【问题讨论】:

  • Ng-repeat 创建它自己的范围,如果您的示例指令也这样做,您是否尝试过 $parent.$parent.$index?
  • 您在访问父索引时遇到了什么具体错误?你在使用指令的 transclude 属性吗?
  • 不显示数字 yes transclude 为真
  • 创建重现问题的演示。见minimal reproducible example
  • 对我来说工作正常...我认为您的代码中还有其他问题。提供 plunker 以便更好地理解代码。

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2012-09-04
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多