背景
最近在用ionic+angularjs做一款应用,期间使用ionic的slidebox时用ng-repeat指定轮播的图片
<ion-slide-box on-slide-changed="slideHasChanged($index)" auto-play="true" does-continue="true" slide-interval=2000 show-pager="true" pager-click="pageClick(index)" active-slide="model.activeIndex" delegate-handle="delegateHandler">
<ion-slide ng-repeat="slideImg in slideImages">
<div class="box">
<img src="{{slideImg}}" style="width: 100%;">
</div>
</ion-slide>
</ion-slide-box>
测试的时候为了方便直接复制的相同的地址:
$scope.slideImages = [
'images/banner1.jpg',
'images/banner1.jpg',
'images/banner1.jpg',
'images/banner1.jpg'
];
结果控制台报错:
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.5.3/ngRepeat/dupes?
解决方案
原因是ngRepeat不允许存在两个相同ID的对象,所以要加上track by
表达式,这里为了方便直接使用索引变量$index
<ion-slide-box on-slide-changed="slideHasChanged($index)" auto-play="true" does-continue="true" slide-interval=2000 show-pager="true" pager-click="pageClick(index)" active-slide="model.activeIndex" delegate-handle="delegateHandler">
<ion-slide ng-repeat="slideImg in slideImages track by $index">
<div class="box">
<img src="{{slideImg}}" style="width: 100%;">
</div>
</ion-slide>
</ion-slide-box>