Shane
Shane

Reputation: 5667

Trigger ng-change on load

I have multiple checkbox being rendered on page, i would like to trigger ng-change() if my checkbox has been checked on load.

<input type="checkbox" ng-true-value="true" 
      ng-false-value="false"
        ng-change="CustomCheckSelect(someValue)" ng-model="model.defaultCheckBox"/>

Using ng-init is causing me problems and throwing errors in console as some of them are not checked.

Upvotes: 3

Views: 6392

Answers (2)

koox00
koox00

Reputation: 2731

From the docs about ngChange:

The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.

Even if you would trigger the ng-change, let's say with ng-model-options:
ng-model-options="{updateOn: 'onload default'}"
it wouldn't get evaluated because you are not changing any value.

If you don't like the ngInit solution you can try manually invoking the function in the controller.

So you have one $scope.model and some of the properties are handled by checkboxes let's say defaultCheckbox and secondaryCheckbox.

To avoid repetition I would store these values in an array and then iterate and call the function CustomCheckSelect by condition:

var checkboxes = ['defaultCheckbox', 'secondaryCheckbox'];

angular.forEach(checkboxes, function(val){
    if ($scope.model[val]) {
        $scope.CustomCheckSelect(val);
    }
})

plunker

Upvotes: 3

Manu Mohan
Manu Mohan

Reputation: 1784

Try this. Write a <div></div> with ng-if and check whether "model.defaultCheckBox" is true or false. Call a method in ng-init from that div. Like-

<div  
    ng-if="model.defaultCheckBox"  ng-init="CustomCheckSelect(somevalue)">
</div>

Upvotes: 6

Related Questions