45

I want to detect if a checkbox has been checked or unchecked when a click is happening on the checkbox.

This is what I have:

<input type="checkbox" ng-model="answers[item.questID]" ng-change="stateChanged()" />

And then in the controller I have:

$scope.stateChanged = function () {
    alert('test');
}

I'm able to fire the alert when I do check/uncheck but how can I detect the state of the checkbox? I did research a bit to find a similar issue but I wasn't able to get what I need.

2 Answers 2

71

You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

Example:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

yes that was the fix, thanks, I'll select your answer in 8 minutes.
0

The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.