简体   繁体   中英

Dirty checkbox still checked when ng-model set to false

I have a simple problem but I don't know how to solve it in AngularJS 1.4. Basically, I have a form with 1 checkbox and 1 button. The button should uncheck the checkbox and set a boolean variable (ng-model of checkbox) to false.

However, I cannot do like this when the checkbox is checked by users (checkbox state is dirty) and the button cannot do anything to uncheck this checkbox .

Any idea to solve this problem?

<button ng-click="uncheckCheckbox()">uncheck</button> 
<input type="checkbox"  ng-model="displayWMSLayer" ng-change="showWMSLayerOnGlobe(displayWMSLayer)"/>

A rough Javascript code to show what functions do:

function uncheckCheckbox() {
    $scope.displayWMSLayer = false;
    alert("Checkbox is unchecked automatically");
}

function showWMSLayerOnGlobe(status) {
    if (status) {
       alert("Checkbox is checked manually");
    } else {
       alert("Checkbox is unchecked manually");
    }
}

Try to use like this way

JS

$scope.checkboxModel = {
  displayWMSLayer: false  
};

HTML

<input type="checkbox"  ng-model="checkboxModel.displayWMSLayer" ng-change="showWMSLayerOnGlobe(checkboxModel.displayWMSLayer)"/>

If i understand your question properly, you just want to have a button to uncheck the checkbox.

In case i am correct then why don't you just try this way ?

HTML:-

 <div ng-app>
  <div ng-controller="TodoCtrl">
   <button ng-click="uncheck()">uncheck</button> 
<input type="checkbox"  ng-model="displayWMSLayer"/>
  </div>
</div>

JS:-

function TodoCtrl($scope) {
    $scope.displayWMSLayer = false;
    $scope.uncheck=function(){
        $scope.displayWMSLayer=$scope.displayWMSLayer?$scope.displayWMSLayer=false:$scope.displayWMSLayer;
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM