Ng model for dynamically loaded elements

I have a list with some elements (like cars) that are dynamic, so it does not have 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 the elements:

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

Now I have a custom object. This object has an array of "cars" inside, where I would like to click all the selected cars and delete it if I turn it off. My object is as follows:

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

, , cars , , . , ng-change, . - ng-model . , . ng- , . ? .

+4
1

cars, change checkbox itemList, .

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

$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;
}
+1

Source: https://habr.com/ru/post/1663972/


All Articles