4

I've got a list with some items (for example cars) which is dynamic, so it hasn't got a fixed length. When I load this list it looks like this:

itemList = [
    { id: 0, name: 'bmw' },
    { id: 1, name: 'audi' },
    { id: 3, name: 'vw' },
    { id: 4, name: 'subaru' },
    { id: 5, name: 'mercedes' }
];

After that, I loop this list in an ng-repeat loop and create some checkboxes, so I can select items:

<div class="item" ng-repeat="item in itemList">
    <input type="checkbox">
    <label>{{item.name}}</label>
</div>

Now I have a user object. This object has an array "cars" within, where I would like push all the selected cars and remove it if I deselect it. My object looks like this:

userObj = [
    { 
      name: 'user1', 
      cars: [] 
    }
];

So when I select a car, it should be pushed into the array cars in my user object and also removed if I deselect it. I know I have to do this with ng-change and this wouldn't be my real problem. My problem is the ng-model for the checkbox. I don't know how to do it the best. I can't use the same ng-model for every list this is pretty logical. What would be the best way? Didn't find any solution on the internet.

webta.st.ic
  • 4,781
  • 6
  • 48
  • 98
  • 1
    afaik, ngModel binds via reference as stated in the [(docs)](https://docs.angularjs.org/api/ng/directive/ngChange), so if you reassign whatever value is bound via ng-model with a new reference, it should update and adjust the value it references appropriately. – ZombieTfk Dec 16 '16 at 15:51
  • 1
    Does this answer your question? http://stackoverflow.com/questions/14514461/how-to-bind-to-list-of-checkbox-values-with-angularjs – François Gautier Dec 16 '16 at 15:58

1 Answers1

1

You could update specific user's cars array, on change of checkbox of each item itemList like below.

Markup

<div class="item" ng-repeat="item in itemList">
    <input type="checkbox" ng-model="item.checked" ng-change="itemChange(user)">
    <label>{{item.name}}</label>
</div>

Code

$scope.itemChange = function(user){
   var selectedCarsIds = $scope.itemList.filter((i) => i.checked).map(item => item.id)
   //update cars array for specific user
   user.cars = selectedCarsIds;
}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299