Reputation: 13
How can i create a new instance of an object with different(unique) hashkey or id for ng-repeat?. I tried to use "track by", but can't get it to work.
My code below:
For each row in the table (could be 5 ,10 ...rows), I want to display the same set of check boxes stored in this list:
$scope.list_of_checkboxes =
[
{
name: "ch1",
properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}]
},
{
name: "ch2",
properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}]
}
];
Once check box is checked i am storing check box object in $scope.table_rows.objects
by using this library:
http://vitalets.github.io/checklist-model/
$scope.table_rows=[{row_1:'row # 1', objects:[]},{row_2: 'row # 2',objects:[]},{row3:'row # 3',objects:[]}]
Check boxes are displayed and functioning fine. However, when i store objects of checked check boxes in $scope.table_rows.objects, they all have the same hashkey. This is the problem. Because, when i display
properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}]
as input fields and update one of the properties values for example table_rows[key].objects[1].v = 30
, the same value getting copied to properties of the same object stored in other rows.
I tried to return new instance (but it doesn't work):
$scope.list_of_checkboxes = function (){
return ([
{
name: "ch1",
properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}]
},
{
name: "ch2",
properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}]
}
])
}
Upvotes: 0
Views: 296
Reputation: 1141
Not the complete implementation but you can try using track by $id(obj) :
HTML :
<div ng-app="myApp" ng-controller="Ctrl">
<table>
<tr ng-repeat=" row in rows track by row.name">
<td ng-repeat="role in roles track by $id(role)" >
<input type="checkbox" checklist-model="user.roles" checklist-value="$id"/> {{role.name}},{{$id}}
</td>
</tr>
</table>
<br><br><br>
user.roles {{ user.roles | json }}
</div>
JavaScript :
var app = angular.module("myApp", ["checklist-model"]);
app.controller('Ctrl', function($scope) {
$scope.rows=[{
name:'first'
},{
name:'second'
},{
name:'third'
}];
$scope.roles =[
{
name: "ch1"
},
{
name: "ch2" }
];
$scope.user = {
roles: []
};
});
Demo : http://jsfiddle.net/FC9c7/78/
Upvotes: 0