0

I'm so new in javascript/angularJS, what I have to do is maybe simple, but I don't really know. I have a checkbox like this :

<input id="myInput" type="checkbox" ng-checked="isChecked">

And now when i click to perform the value isChecked in my model is updated correctly. This is the simple part. Now I have to add a control on the oncheck event. In other words: before that isChecked is being updated, the value in the model I have to perform a validation and if the validation return false, the value isChecked should not be updated.

1 Answer 1

2

You could use ng-model and ng-change instead of ng-checked to perform a function when the checkbox is checked or unchecked:

<input id="myInput" type="checkbox" ng-model="myModel.isChecked" ng-change="checkboxChanged()">

So that, in your controller, you can handle the event with a function:

$scope.myModdel = {
  isChecked = false    //setting initial value for checkbox
};
$scope.checkboxChanged = function() {
  if( some validation error && $scope.myModel.isChecked ) {
    $scope.myModel.isChecked = false;  // uncheck checkbox
  }
}

Be sure not to use both ng-model and ng-checked as described in the docs:

Note that [ng-checked] should not be used together with ngModel, as this can lead to unexpected behavior.

You can solve your CSS issue by using ng-class like so:

<input id="myInput" type="checkbox" ng-model="myModel.isChecked" ng-change="checkboxChanged()" ng-class="{'my-class-name': myModel.isChecked }">
Sign up to request clarification or add additional context in comments.

4 Comments

I need ng-checked, because I have a css that uses the checked attribute. I thought to use ng-click and ng-checked : <input id="myInput" type="checkbox" ng-model="isChecked" ng-checked="checkboxChanged()"> but I think this is an error like use both ng-model and ng-checked.
Ah, I see. Alternatively you could set up a watch on the isChecked scope variable.
A watcher has it's own issues, though. I still recommend the first answer and using ng-class instead of the checked property to solve your styling issue.
I hear that watcher is much heavy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.