Lea
Lea

Reputation: 281

ng-model value switching from false to undefined instead of true when checkbox is clicked

I'm struggling with an input checkbox and the ng-model. I'm initializing my variable with false, setting it as the ng-model on the input checkbox. When displaying it, the value is false. After clicking on the checkbox the value changes to undefined instead of true.

Here is my code:

<div ng-app="app" ng-controller="Controller">
    <input id="check" type="checkbox" ng-model="model.noExpiry" ng-click="model.clickCheck()">Click
    <p>{{model.noExpiry}}</p>
</div>


var module = angular.module("app",[]);

    module.controller("Controller", function ($scope) {
      $scope.model = {};
      $scope.model.noExpiry = false; 

      $scope.model.clickCheck = function(){
        console.log($scope.model.noExpiry);
      }
});

If I remove the ng-model and change the model.clickCheck function into the following, it changes correctly the variable from false to true and vice versa:

$scope.model.clickCheck = function(){

    if($scope.model.noExpiry) {
        $scope.model.noExpiry = false;
    }
    else {
        $scope.model.noExpiry = true;
    }

    console.log($scope.model.noExpiry);
}

When I initialize the model.noExpiry with true, the checkbox turns out to be checked but when unchecking and checking it again, it changes to false and then again to undefined.

Does anybody have an idea why the variable does not change to true but instead to undefined?

AngularJs Version: 1.5.5

Upvotes: 0

Views: 948

Answers (1)

I. Ahmed
I. Ahmed

Reputation: 2534

The reason is $scope.model is undefined. So, property $scope.model.noExpiry is not valid. Just added $scope.model = {}; in your controller to make valid object.

Please check the final updated code:

var module = angular.module("app",[]);
    
    
    module.controller("Controller", function ($scope) {
      $scope.model = {};
      $scope.model.noExpiry = false;

      $scope.model.clickCheck = function(){
        console.log($scope.model.noExpiry);
      }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Controller">
    <input id="check" type="checkbox" ng-model="model.noExpiry" ng-click="model.clickCheck()">Click
    <p>{{model.noExpiry}}</p>
</div>

Upvotes: 0

Related Questions