gpt4 book ai didi

javascript - ng-repeat 无法处理具有非连续数字索引的数组?

转载 作者:行者123 更新时间:2023-11-30 07:23:31 25 4
gpt4 key购买 nike

我是 Angular JS 的新手,想用它来处理由 ajax 传递的 json。首先,我编写了这段测试代码以确保数据可以正确显示:

<head>
<script src="path/to/angular.js"></script>
<script>
var app = angular.module('pageApp', []).config(function($interpolateProvider){
$interpolateProvider.startSymbol('<<').endSymbol('>>');
});
</script>
</head>
<body ng-app="pageApp">
<div class="container" ng-controller="tagging">
Text input:<textarea ng-model="description" ng-change="checkTag()" required></textarea><br>
Tag found om database: <span ng-repeat="tag in tags"> << tag >> </span><br>
</div>
</body>

<script>
//$http is not used now but will be used in the actual ajax handling.
function taggingController($scope, $http) {
$scope.tags = [];
$scope.checkTag = function () {
var hardCode = [];
hardCode[1] = "one";
hardCode[3] = "three";
hardCode[5] = "five";
angular.forEach(hardCode, function(value, key) {
console.log($scope.tags[key]);
$scope.tags[key] = value
});
};
};

app.controller("tagging", taggingController);

</script>

但是,代码不起作用并给出以下错误:

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: tag in tags, Duplicate key: undefined:undefined, Duplicate value: undefined

当数组更改为连续数字的索引时,它起作用了。即

hardCode[1] = "one";
hardCode[2] = "three";
hardCode[3] = "five";

我是不是漏掉了什么或者 Angular JS 根本没有能力处理非连续数字索引数组?

最佳答案

Angular 会尝试确定对象是否是类似于对象的数组。一旦确定,它就会根据第一个谓词设置其 trackBy 属性。然后它构建它的集合。

if (isArrayLike(collection)) {
collectionKeys = collection;
trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
} else {
trackByIdFn = trackByIdExpFn || trackByIdObjFn;
// if object, extract keys, in enumeration order, unsorted
collectionKeys = [];
for (var itemKey in collection) {
if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
collectionKeys.push(itemKey);
}
}
}

之后它使用常规的 for 循环

for (index = 0; index < collectionLength; index++) {

你可以在这里看到代码: angular-ngRepeat directive

因为 Angular 确定您正在使用类似对象的数组,它会尝试逐个索引地遍历数组,并遇到未定义的情况。如果您必须使用其中带有“孔”的数组并使用 ng-repeat,您应该考虑使用对象而不是数组:

        var hardCode = {};
hardCode["1"] = "one";
hardCode["3"] = "three";
hardCode["5"] = "five";

关于javascript - ng-repeat 无法处理具有非连续数字索引的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28145155/

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