Reputation: 72
I have some logic that on certain senario, I want the first check box to be alway checked. So if user tries to uncheck it, I want to use ng-click to change the ng-model binded to the checkbox to 'true'. But the checkbox is still being unchecked....
How do I achieve keep the checkbox remains checked based on the ng-model's value, without using something like angular.element(elem).attr("checked", true)
<input type = 'checkbox' ng-model = 'checkboxValue' ng-click = "handler"/>
in the controller
$scope.checkboxValue = false;
$scope.handler = function(){
$scope.checkboxValue = true;
}
I want the checkbox remain checked since the ng-model checkboxValue is true...but apparently I missed something here
Here's the plunker:http://plnkr.co/edit/WbjZilFLDfbP3mQ4oMgx?p=preview
I stepped into the call stack, looks like I set the ng-model to true, then during $digest, the ng-model is set based on the checkbox's status : checked or unchecked. So it is more like one way binding: bindding the ng-model based on the checkbox status?
Upvotes: 3
Views: 11458
Reputation: 362
If you don't want to allow users to uncheck the check box, you can use ng-disabled
directive.
A plunk with fork from your plunk. http://plnkr.co/edit/Y2kUYN2F5bZboaPJWMd8?p=preview
Upvotes: 1
Reputation: 3184
You can watch the checkboxValue for changes and then change it however you like rather than hooking in through ng-click. If you wanted behavior where the checkbox is initially false, and then true forever once clicked you could do something like:
$scope.checkboxValue = false;
$scope.$watch('checkboxValue', function(newValue, oldValue){
$scope.checkboxValue = newValue || oldValue;
});
Here's the required changes to your plunker: http://plnkr.co/edit/XPZXSzsnaZDGlIi8mxnM?p=preview
Upvotes: 0
Reputation: 33735
Why not simply use ng-change
to call some logic with each change to the checkbox state?
Upvotes: 1