webta.st.ic
webta.st.ic

Reputation: 5169

ng-model for dynamic loaded items

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.

Upvotes: 4

Views: 129

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

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

Upvotes: 1

Related Questions