AngularJS ng-repeat使用及注意事项

用法:ng-repeat="extension";

extension(表达式) 定义了如何循环集合。

表达式实例规则:

1. x in records

2. (key,value) in myObj

3. x in records track by $id(x)

 

我们可以使用ng-repeat指令遍历一个JavaScript数组,当数组中有重复元素的时候,AngularJS会报错:

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: number:1

如下面的代码就会报错:

<!DOCTYPE html>
<html ng-app="app" ng-controller="appCtrl">
<head>
    <title>Self Document</title>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    var app = angular.module('app',[]);
    app.controller('appCtrl',function($scope,$element){
        $scope.dataList = [1,2,1];
    });
</head>
<body>
    <div ng-repeat="value in dataList">
        <p>
            <span ng-bind="value"></span>
        </p>
    </div>
</body>
</html>

这是因为ng-repeat不允许集合中存在两个相同id的对象。

For example: item in items is equivalent to item in items track by $id(item). This implies that the DOM elements will be associated by item identity in the array.

对于数字或者字符串等基本数据类型来说,它的id就是它自身的值。因此数组中是不允许存在两个相同的数字的。为了规避这个错误,需要定义自己的track by表达式。

// 业务上自己生成唯一的id
1. item in items track by item.id

//或者直接拿循环的索引变量$index来用
2. item in items track by $index

 

另外:如果集合是Javascript对象类型数据,那么就算值一摸一样,ng-repeat也不会认为这是相同的对象。

如果将上面的代码中dataList,那么是不会报错的。比如$scope.dataList = [{"num":10},{"num":10}];

 

参考文章:http://blog.csdn.net/aitangyong/article/details/44100921

posted @ 2017-05-11 21:41  以乐之名  阅读(5011)  评论(0编辑  收藏  举报