亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

AngularJS ng-repeat指令中使用track by子語句解決重復(fù)數(shù)據(jù)遍歷錯誤問題

 更新時間:2017年01月21日 11:54:57   作者:aitangyong  
這篇文章主要介紹了AngularJS ng-repeat指令中使用track by子語句解決重復(fù)數(shù)據(jù)遍歷錯誤問題,結(jié)合實例形式分析了ng-repeat指令遍歷JavaScript數(shù)組錯誤的原因與相關(guān)解決技巧,需要的朋友可以參考下

本文實例講述了AngularJS ng-repeat指令中使用track by子語句解決重復(fù)數(shù)據(jù)遍歷錯誤問題。分享給大家供大家參考,具體如下:

我們可以使用ng-repeat指令遍歷一個JavaScript數(shù)組,當(dāng)數(shù)組中有重復(fù)元素的時候,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。下面的代碼就會報錯:

<html>
 <head>
  <script src="angular-1.2.2/angular.js"></script>
  <script>
     function rootController($scope,$rootScope,$injector)
     {
      $scope.dataList = [1,2,1];
     }
  </script>
 </head>
 <body ng-app ng-controller="rootController">
    <div ng-repeat="data in dataList">
      {{data}}
    </div>
 </body>
</html>

這是因為ng-Repeat不允許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.

對于數(shù)字或者字符串等基本數(shù)據(jù)類型來說,它的id就是它自身的值。因此數(shù)組中是不允許存在兩個相同的數(shù)字的。為了規(guī)避這個錯誤,需要定義自己的track by表達式。

// 業(yè)務(wù)上自己生成唯一的id
item in items track by item.id
//或者直接拿循環(huán)的索引變量$index來用
item in items track by $index

如果是javascript對象類型數(shù)據(jù),那么就算內(nèi)容一摸一樣,ng-repeat也不會認(rèn)為這是相同的對象。如果將上面的代碼中dataList,那么是不會報錯的。比如$scope.dataList = [{"age":10},{"age":10}];

更多關(guān)于AngularJS相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《AngularJS入門與進階教程》及《AngularJS MVC架構(gòu)總結(jié)

希望本文所述對大家AngularJS程序設(shè)計有所幫助。

相關(guān)文章

最新評論