gpt4 book ai didi

javascript - AngularJS 嵌套 ng-repeats 与单个索引?

转载 作者:行者123 更新时间:2023-11-30 08:49:33 25 4
gpt4 key购买 nike

使用 Angular 1.0.7,如何为嵌套的 ng-repeat 指定单个索引,以便内部数组中的每个项目都获得一个连续的索引值? (即所有内部数组中所有元素的 0、1、2、3 等)

为了说明:

<ul>
<li ng:repeat="item in arr1">
<ul>
<li ng:repeat="child in item.children">{{consecutiveIndex++}}</li>
</ul>
</li>
</ul>

我尝试通过以下方式实现它:

var cindex= -1;
$scope.cindex= function () {
console.log('cindex', cindex);
return ++cindex;
};

HTML:

<ul>
<li ng:repeat="item in arr1">
<ul>
<li ng:repeat="child in item.children">{{index()}}</li>
</ul>
</li>
</ul>

我在使用这个时遇到了非常奇怪的 AngularJS 错误(相信我,你不想知道)。

我还发现(根据控制台输出),即使对于只有 4 个元素的数组,ng-repeat 也会命中我的 cindex() 函数 80 多次。意思不是 0、1、2 和 3 - 我得到了 84、85、86 和 87。

有什么想法吗?

最佳答案

您不能依赖于您的 {{index()}} 被调用固定次数。每当 angular 决定对范围进行脏检查时,它将运行所有绑定(bind)。

您可以根据其他索引生成值。 Demo plunker

HTML

<body ng:controller="MainCtrl">
<ul>
<li ng:repeat="item in arr1">
<ul ng:init="parentIndex = $index">
<li ng:repeat="child in item.children">{{getConsecutiveIndex(parentIndex, $index)}}</li>
</ul>
</li>
</ul>
</body>

JS

app.controller('MainCtrl', function($scope) {
$scope.arr1 = [{children:[0,1,2,3]}, {children:[4,5]}, {children:[6,7,8]}];

$scope.getConsecutiveIndex = function(parentIndex, $index) {
var total = 0;
for(var i = 0; i < parentIndex; i += 1) {
total += $scope.arr1[i].children.length;
}
return total + $index;
}
});

关于javascript - AngularJS 嵌套 ng-repeats 与单个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19126905/

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