欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

我們可以使用ng-repeat指令遍歷一個(gè)JavaScript數(shù)組,當(dāng)數(shù)組中有重復(fù)元素的時(shí)候,AngularJS會(huì)報(bào)錯(cuò):

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。下面的代碼就會(huì)報(bào)錯(cuò):

<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>

這是因?yàn)閚g-Repeat不允許collection中存在兩個(gè)相同Id的對(duì)象。

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.

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

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

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

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

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

相關(guān)文章

最新評(píng)論