Angularjs: checkbox and ng-change

mpeg90 picture mpeg90 · Apr 28, 2017 · Viewed 54.2k times · Source

I have problems to understand how ng-change works. I have a list of user to invite to join an auction. I want to do this with a checkbox. If the user is checked, his name has to be saved into an array. And later i will invite them(i just know how to do this). But i don't understand how to use the checkbox. I did something like this:

<ul class="list-group" ng-repeat="user in users">
    <li class="list-group-item" ng-hide="user.name == profile">
        <img ng-src="{{user.img}}" class="image2" >
        <div class="username"> {{user.name}}</div>
        <div class="userrole"> {{user.role}} </div>
        <div class="usercompany">{{user.company}}</div>
        <input type="checkbox"  ng-model="isChecked" ng-change="insertinvited(user.name)">
    </li>
</ul>

And in my controller:

$scope.invited = [];
$scope.insertinvited= function (name) {
    if($scope.isChecked){
        $scope.invited.push(name)
    } else {
        console.log($scope.invited);
    }
};

But this is not working, in the console the array is always empty.

Answer

Mistalis picture Mistalis · Apr 28, 2017

The problem in your code is that your checkbox model (isChecked) is used by all the users you ngRepeated on:

<ul class="list-group" ng-repeat="user in users">
    ...
    <input type="checkbox" ng-model="isChecked" ng-change="insertinvited(user.name)">
</ul>

I suggest you to have a checkbox model for each user:

<input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">

Note that in your ng-change, I pass the whole user object, and not only user.name (because I will also need the user.isChecked property).


Here is the "new" insertinvited() function:

$scope.insertinvited = function(user) {
    if(user.isChecked) {
        $scope.invited.push(user.name);
    } else {
        var toDel = $scope.invited.indexOf(user.name);
        $scope.invited.splice(toDel, 1);
    }
}