gpt4 book ai didi

angularjs - ng-if 导致 $parent.$index 被设置为 $index

转载 作者:行者123 更新时间:2023-12-01 12:39:12 24 4
gpt4 key购买 nike

我有一个 ng-repeater,其中包含一个嵌套的 ng-repeater。在嵌套的中继器中,我试图跟踪父 $index 值,这工作正常。但是,当我在引用 $parent.$index 的同一元素中引入 ng-if 时,父索引设置为子索引。对此有什么想法吗?代码运行here .举个例子,我点击父 0 的索引 1 并获取索引 1 父 1 作为索引。

JavaScript

var myApp = angular.module('myApp', []);

myApp.controller('ctrl', function($scope) {

$scope.arr = [["a","b","c"],["d","f","e"],["f","h","i"]];

$scope.logIndex = function(index, parent) {
console.log("index: " + index + ", parent: " + parent);
};

});

HTML

<ul>
<li ng-repeat="i in arr">
<ul>
<li ng-repeat="j in i">
<span ng-click="logIndex($index, $parent.$index)" ng-if="$index > 0">{{ j }}</span>
</li>
</ul>
</li>
</ul>

最佳答案

那是因为 ng-if 在元素上创建了一个子作用域,所以 $parent 实际上是它直接的 ng-repeat 的子作用域,而不是父作用域,并且$index 再次是从其直接父级(即第二个 ng-repeat 的子范围)继承的相同 $index。您可以使用 ng-init别名 ng-repeat 的特殊属性并使用该属性而不是使用 $parent。

   <li ng-repeat="i in arr" ng-init="parentIndex=$index">
<ul>
<li ng-repeat="j in i">
<span ng-click="logIndex($index, parentIndex)" ng-if="$index > 0">{{ j }} </span>
</li>
</ul>
</li>

Demo

关于angularjs - ng-if 导致 $parent.$index 被设置为 $index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26658679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com