Search code examples
angularjscheckboxangularjs-ng-clickangularjs-ng-change

How do I reverse a checkbox state to make it unchecked (AngularJS)?


I basically want that when the user clicks on a checkbox, their decision is immediately reversed and the checkbox is unchecked. The code below is not working. I tried other variations like value = !value instead of value = false and tried initializing another controller variable to be equal to the checkbox variable and changing the other controller variable. None of this works; basically, I cannot set the checkbox state unless the application is first being initialized.

HTML code:

<input type="checkbox" ng-model="avariabledefinedincontroller" ng-click="changemystate(avariabledefinedincontroller)">

Controller code:

$scope.avariabledefinedincontroller = false;


$scope.changemystate = function(value){
  if (value == true) {
    value = false;

 }

 else {
   value = value;
 }

};

Solution

  • The value passed into changemystate will be the value the checkbox has when it is clicked. So if you want it to stay at that value, you can set up a timeout to restore it to that value. No negation is needed.

    Also, assigning a value to value will do nothing. You have to modify the scope variable. If you want to identify the scope variable for the item that was clicked, you can pass in a string:

    function MyController($scope, $timeout) {
      $scope.mybool = false;
    
      $scope.changemystate = function(key) {
         var value = $scope[key];
         $timeout(function () {
             $scope[key] = value;
         }, 0);
      };
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
    <div ng-app="" ng-controller="MyController">
      <input type="checkbox" ng-model="mybool" ng-click="changemystate('mybool')" />
      {{mybool}}
    </div>