简体   繁体   中英

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 ?

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 . Unfortunately, it is currently not possible to use ng-checked on the md-checkbox directive ( see this bug ). So you will have to use the ng-model . The following code should help you.

HTML

<md-checkbox md-no-ink="true" ng-model="selected[$index]" ng-repeat="brand in brands track by $index">
    {{brand}}
</md-checkbox>

Is Samsung selected: {{isSelected('Samsung')}}

JS

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

$scope.isSelected = function(brand) {
    var brandIndex = $scope.brands.indexOf(brand);
    return $scope.selected[brandIndex]
};

Please notice that each checkbox needs its own model. Before you used the $scope.value as a single model for all of the checkboxes - in such case they would be checked/unchecked all at once.

I believe the code above is what you are looking for. Feel free to make a comment if I missed the point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM