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

情到浓时终转凉″ 提交于 2019-12-07 16:00:31

问题


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?


回答1:


Simply use ng-change instead of ng-click

Here is a DEMO




回答2:


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




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/24423893/angular-checkbox-using-ng-click-to-reset-the-ng-model-that-is-binded-to-the-chec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!