Abh*_*der 6 javascript angularjs
我在SO中没有看到任何问题,讨论在ng-repeat中不允许重复.我的问题略有不同.在我的情况下,我很困惑,因为即使数组中有重复的对象,我也没有收到错误
这是我的HTML代码
<table>
<tr ng-repeat="item in items">
<td> {{ item.email}}</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
这是填充数组的代码
app.controller('MainCtrl', function($scope) {
$scope.items=[];
$scope.items.push({
"id":"1",
"email":"a@b.com"});
$scope.items.push({
"id":"1",
"email":"a@b.com"});
$scope.items.push({
"id":"2",
"email":"x@y.com"});
$scope.items.push({
"id":"2",
"email":"x@y.com"});
});
Run Code Online (Sandbox Code Playgroud)
根据我的理解,我应该得到错误,并且数组中有重复的对象
然而它变得完美呈现.这是plunker链接
显然我遗漏了一些基本的东西.有人能指出我在理解方面的差距吗?
编辑
这是我在我的应用程序中面临的问题(只有电子邮件ID因为显而易见的原因而被更改)
ExampleApp.filter("extractEmail",function(){
return function(items){
//console.log("test" + input[0].highlight.file[0]);
var filtered = [];
console.log(" items == " + items);
angular.forEach(items, function(item){
if (item){
var obj = item.highlight.file[0].toString().match(/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/);
if (obj) {
//console.log(obj[0]);
filtered.push(obj[0]);
}
}
});
console.log(filtered);
return filtered;
}
});
Run Code Online (Sandbox Code Playgroud)
我的console.log打印 [“a@gmail.com", “a@gmail.com", “b@gmail.com", “b@gmail.com"]
我得到的错误
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: x in clusterState| extractEmail, Duplicate key: string:a@b.com, Duplicate value: “a@b.com"
Run Code Online (Sandbox Code Playgroud)
我用类似的代码更新了plunker.无法重现
第二次编辑
问题在于我使用的版本:Angular JS 1.0.x支持重复项无法重现 http://plnkr.co/edit/qrOez7aZ7X1jsOrmkfiP?p=preview
随着后期版本能够重现
javascript中的对象通过引用进行比较,而不是通过值进行比较.
如果对象的内容与另一个对象的内容完全相同,则无关紧要,如果引用不指向同一对象,则它们是不同的.
例如:
// In this case "var a" and "var b" points to different objects.
var a = {};
var b = {};
a == b; // false
// Here, they points to the same one
var a = {};
var b = a;
a == b; // true
Run Code Online (Sandbox Code Playgroud)
如果您需要每个条目都是独特的,您必须自己检查每个条目.
Angular ngRepeat有一个语法变体,用于track by让您决定哪个条目是不同的(或重复的).
<div ng-repeat="entry for entries track by entry.id">{{entry.email}}</div>
Run Code Online (Sandbox Code Playgroud)
这些项目被认为是不相同的,因为它们指向不同的引用.
如果您要按ID跟踪,那么您将收到错误,因为ID相等.
<tr ng-repeat="item in items track by item.id">
<td> {{ item.email}}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
看到这个小提琴:http://jsfiddle.net/aj_r/7d4n9z0u/
| 归档时间: |
|
| 查看次数: |
3535 次 |
| 最近记录: |