angularjs - ngRepeat with custom index coming up blank -
i'm using large amount of arrays in large form in application. in order make splicing out specific data datasets based on user's selections, i've structured arrays example:
var userlist = []; userlist[user1.id] = user1; userlist[user2.id] = user2;
this lets me splice out specific elements without looping through entire collection using:
userlist.splice(user1.id, 1);
however, when try make list of users in html using ng-repeat statement, comes blank. html is:
<div data-ng-repeat="user in userlist">{{user.name}}</div>
i suspect ngrepeat uses 0,1,2.. default , doesn't know how handle custom indexes. i've checked several sources can't make sense of things. did work when added users pushing them array instead of assigning them specific index, know rest of code works fine.
help? d:
edit:
the addition of trackby "track user.id" didn't fix it.
your code isn't working because array's indexes zero-based meaning, go 0, 1, 2, ... n , you're trying put alphanumeric indexes if check below code snippet length of array zero.
var user1 = { id: 'a1b2', name: 'pete' }; var user2 = { id: 'a2b3', name: 'jeff' }; var userlist = []; userlist[user1.id] = user1; userlist[user2.id] = user2; console.log(userlist); console.log('length: ' + userlist.length); console.log(userlist['a1b2']); console.log(userlist.a1b2); // behaving javascript object not array property set using userlist[user2.id] = user2;
so need set data structure properly, can set follows specifying index of array or using push
function on array add new item array.
var user1 = { id: 'a1b2', name: 'pete' }; var user2 = { id: 'a2b3', name: 'jeff' }; $scope.userlist = []; $scope.userlist[0] = user1; // $scope.userlist.push(user1); $scope.userlist[1] = user2; // $scope.userlist.push(user2);
i suggest change collection name userlist
users
looks clean, don't need suffix collection list keyword think looks untidy, make name plural.
angular .module('demo', []) .controller('defaultcontroller', defaultcontroller); function defaultcontroller() { var vm = this; var pete = { id: 'a1b2', name: 'pete' }; var jeff = { id: 'a2b3', name: 'jeff' }; vm.users = []; vm.users[0] = pete; vm.users[1] = jeff; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="demo"> <div ng-controller="defaultcontroller ctrl"> <div ng-repeat="user in ctrl.users"> <span>{{user.id}}, {{user.name}}</span> </div> </div> </div>
Comments
Post a Comment