Sohan Shirodkar Sohan Shirodkar - 6 months ago 230
Javascript Question

Why is `ng-checked` not working with `ng-change`?

I have a list of checkboxes. Whenever I click on a checkbox I want to call a function depending on whether it was checked or unchecked. This is achieved using

ng-change


At the same time I also have
ng-checked
that helps me to uncheck a checkbox using a button.

Following is the implementation:

<md-checkbox md-no-ink="true" ng-checked="selected.indexOf(brand) > -1" ng-change="value?add(brand):remove(brand)" ng-model="value" ng-repeat="brand in brands">
{{brand}}
</md-checkbox>

<md-button ng-click="fun('Spice')">Uncheck</md-button>


The controller code is as follows:

$scope.brands = ['Apple','Samsung','Motorolla','Nokia','Micromax','Spice'];
$scope.value = false;
$scope.selected = [];

$scope.fun = function(x){
console.log("Unchecking "+x);
}
$scope.add = function(x){
$scope.selected.push(x);
}
$scope.remove = function(x){
var index = $scope.selected.indexOf(x);
$scope.selected.splice(index,1);
}


There is a similar question on Stackovrflow, but it had issue regarding missing ng-model on the checkboxes. I have included
ng-model
here.

Why is this not working? Have I done anything wrong ?

Answer

The official documentation states that

Note that this directive should not be used together with ngModel, as this can lead to unexpected behavior.

You should decide whether to use the ng-model or ng-checked.

Comments