angular中为什么会使用track by 实现ng-repeat嵌套

时间:2022-12-25 23:14:40


<div ng-repeat="links in slides">    <div ng-repeat="link in links track by $index">{{link.name}}</div></div>

slides是一个二维数组,我以上的代码会报错Error: [ngRepeat:dupes]

$http.get('index.php?option=com_mtree&task=ajax.load').success(function(response) {    if(response.status) {        $scope.links = response.links;        if(typeof response.links != 'undefined') {            var slides = [], slide;            for(var i=0; i<response.links.length;) {                slide = [];                for(var c=0; c<3&&c<response.links.length; c++, i++) {                    slide.push(response.links.indexOf(i));                }                slides.push(slide);            }            $scope.slides = slides;        }        /* setTimeout(function(){ jQuery('.saved-list .slideshow').cycle('destroy'); jQuery('.saved-list .slideshow').cycle(); }, 0); */    }});

Error: [ngRepeat:dupes]这个出错提示具体到题主的情况,意思是指数组中有2个以上的相同数字。ngRepeat不允许collection中存在两个相同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表达式。例如:item
in items track by item.id
或者item in items track by fnCustomId(item)。嫌麻烦的话,直接拿循环的索引变量$index来用item in items track by $index

<div ng-repeat="links in slides">    <div ng-repeat="link in links track by $index">{{link.name}}</div></div>

slides是一个二维数组,我以上的代码会报错Error: [ngRepeat:dupes]

$http.get('index.php?option=com_mtree&task=ajax.load').success(function(response) {    if(response.status) {        $scope.links = response.links;        if(typeof response.links != 'undefined') {            var slides = [], slide;            for(var i=0; i<response.links.length;) {                slide = [];                for(var c=0; c<3&&c<response.links.length; c++, i++) {                    slide.push(response.links.indexOf(i));                }                slides.push(slide);            }            $scope.slides = slides;        }        /* setTimeout(function(){ jQuery('.saved-list .slideshow').cycle('destroy'); jQuery('.saved-list .slideshow').cycle(); }, 0); */    }});

Error: [ngRepeat:dupes]这个出错提示具体到题主的情况,意思是指数组中有2个以上的相同数字。ngRepeat不允许collection中存在两个相同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表达式。例如:item
in items track by item.id
或者item in items track by fnCustomId(item)。嫌麻烦的话,直接拿循环的索引变量$index来用item in items track by $index