Vivek V Dwivedi Vivek V Dwivedi - 2 months ago 8
AngularJS Question

How to define a model for dynamically created checkboxes in angular

I am creating a table of users where I want to add a checkbox on each row and a delete button. When I click the delete button, I want to delete all users who were selected.

Now I am creating these user entries from an API response which gives me say id, name and email.

So my view looks something like this:

<tr ng-repeat="user in MyCntrl.data.users track by $index">
<td><input type="checkbox"></td>
<td>{{user.name}}</td>
<td>{{user.email}}</td>
</tr>


What I want in my controller is to have an object with id of all the users for whom the checkbox was clicked.

Even if I create an object and assign it as model for checkbox, how do I add a key as id in that object?

Answer

You could simply do <input type="checkbox" ng-model="user.isSelected">

And then just filter MyCntrl.data.users for those that have isSelected === true