Mawg
Mawg

Reputation: 40140

AngularJs CheckBox conundrum

My view has

<input type="checkbox" class="check_box" ng-model="campaign.paused"  
       ng-click="CampaignPauseClicked(campaign, $event)" />

<p>campaign.paused == {{campaign.paused}}</p>                           

with the <p> being for debugging. It shows false, as it shoudl, given the data, but in the controller

$scope.CampaignPauseClicked = function(campaign, $event)
{
    campaign.paused = ! campaign.paused;

when I breakpoint on the first code line, the value of campaign.paused is true (!).

I have searched the code and campaign.paused is not being written elsewhere.

Any idea what could be happening here?


[Update] I am using an ng-click fucntion, which I have not shown in its entirity, because I need it to "swallow" the $event and prevent it from propogating to the parent.

Upvotes: 2

Views: 49

Answers (2)

Sarantis Tofas
Sarantis Tofas

Reputation: 5167

Also you can replace the ng-click with the ng-change directive since you are using a checkbox. ng-change will run everytime the checkbox state is changed (checked/unchecked)

<input type="checkbox" class="check_box" ng-model="campaign.paused"  
       ng-change="CampaignPauseChanged ($event)" />

<p>campaign.paused == {{campaign.paused}}</p>  

And in your controller:

$scope.CampaignPauseChanged = function(event)
{
    console.log(campaign.paused)
    console.log(event)
}

Another option would be the ng-checked directive here is an example in this plunker. As you can clearly see the checkbox model returns true only if it is checked.

Upvotes: 1

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

That's because ng-model is updating the value when you click the checkbox. You're undoing what Angular is doing for you.

If you want to do it by yourself in your $scope.CampaignPauseClicked function, remove the ng-model part from the html.

Otherwise, you can let Angular do its thing, leave the ng-model="campaign.paused" clause, and remove the first line from your ng-click callback.

Upvotes: 2

Related Questions