snailclimbingtree
snailclimbingtree

Reputation: 72

angular checkbox using ng-click to reset the ng-model that is binded to the checkbox, thus prevent the checkbox from being unchecked

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

Answers (4)

Darshan Joshi
Darshan Joshi

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

iJade
iJade

Reputation: 23791

Simply use ng-change instead of ng-click

Here is a DEMO

Upvotes: 5

dustyrockpyle
dustyrockpyle

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

ŁukaszBachman
ŁukaszBachman

Reputation: 33735

Why not simply use ng-change to call some logic with each change to the checkbox state?

Upvotes: 1

Related Questions