Rutwick Gangurde
Rutwick Gangurde

Reputation: 4912

Angular Js - Checkbox model not toggling on ng-change?

I have a simple checkbox like this:

<input type="checkbox" name="userGroup" ng-model="selectedAll" ng-change="selectAll();"></input>

I'm initiating the selectedAll model to false in my controller. In my selectAll() function, I log the value of the flag. But it stays false, doesn't update when I check and uncheck the checkbox. Any reason and solution for this?

Update:

My controller's code:

$scope.selectedAll = false;

$scope.selectAll = function() {
    console.log($scope.selectedAll);
}

Upvotes: 0

Views: 2174

Answers (3)

Nitsan Baleli
Nitsan Baleli

Reputation: 5458

try using the 'dotted' ng-model:

<input type="checkbox" name="userGroup" ng-model="obj.selectedAll" ng-change="selectAll();"></input>

-

$scope.obj = {
  selectedAll: false
}

$scope.selectAll = function() {
  console.log($scope.obj.selectedAll);
}

Upvotes: 3

Rutwick Gangurde
Rutwick Gangurde

Reputation: 4912

I found out the issue. I'm using angular-ui-router for routing. The checkbox in question is in one state view (View B), which is controlled by this controller. The controller is used by some other state view (View A) as well. In my state configuration, I had specified this as the controller for the View A, but not for the View B, because it is the child of view A and it is supposed to inherit the controller. Just specified the controller explicitly for view B and everything started working.

To simplify:

A (normal view) > B(child view, contains checkbox)

.state('viewa', {
    url: '/viewa',
    templateUrl: '...',
    controller: 'someCtrl'
})

.state('viewa.viewb', {
    url: '/viewb',
    templateUrl: '...',
    controller: 'someCtrl' //ADDED THE CONTROLLER HERE
});

I hope this helps someone who is using angular ui router and faces the same problem.

Upvotes: 0

dhavalcengg
dhavalcengg

Reputation: 4713

here I have created a plnkr

<input type="checkbox" name="userGroup" ng-model="selectedAll" ng-change="selectAll();"></input>
{{selectedAll}}

Its changing flag also i am getting updated value on ng-change

Upvotes: 0

Related Questions