简体   繁体   中英

Switching between arrays with ng-repeat

Right now I have 3 arrays I want to toggle between with my ng-repeat:

$scope.fooDataObj = {
array1:[{name:'john', id:'1'},{name:'jerry', id:'2'}],
array2[{name:'bill', id:'1'},{name:'tom', id:'2'}],
array3:[]
}

and my ng-repeat:

<li ng-repeat="data in fooDataObj track by data.id"></li>

So all I want to do is dynamically switch between my arrays of data within my object in the most performant way.

So basically when some clicks <button></button> it will change from using array1 in the ng-repeat to array2 .

I've accomplished this by setting ng-repeat="data in fooData" then on click triggering $scope.fooData = fooDataObj.array1 . But this is not very performant. Especially when switching between the populated arrays to the empty array.

You could just switch the key and use bracket notation in the ng-repeat source.

 <li ng-repeat="data in fooDataObj[vm.source] track by data.id"></li>

and on button click set vm.source to text array1, array2, array3 . If you want to make it dynamic derived keyname instead of hardcoding then just get the keys from the object as Object.keys(fooDataObj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM