aadu
aadu

Reputation: 3254

AngularJS: Detecting which checkbox in an ngRepeat is checked/unchecked and calling a function

I think I'm trying to do something relatively simple in Angular but for some reason I can't get my head perfectly around ngClick, ngModel, ngChange or ngChecked to solve it.

I have a whole bunch of repeated checkboxes and when one is checked, a function alerts one thing and when its unchecked, the function alerts a different thing. Here's some pseudo code:

HTML:

<div id="topic" ng-repeat="50 times">
    <input type='checkbox' ng-model='???' ng-click='myFunc($index)' />
</div>

Script:

function myFunc(index) {
    if (checkbox == checked) {
      alert('checkbox ' + index + 'checked!');
    }
    else {
      alert('checkbox' + index + 'unchecked!');
    }
}

So the problem is I can't figure out how to tell which checkbox in the repeat is checked and when it's unchecked. Anyone any ideas?

Upvotes: 0

Views: 9800

Answers (2)

onkar patil
onkar patil

Reputation: 1

Ng-model gets called after ng-click. so you can clear model on ng-click and its done. nd-model will bing the value after ng-click

Javascript Code:

 for (var i = 0; i < $scope.sunday_workshop.length; i++) {              
                $scope.sunday_workshop[i].flag = false;                 
            }

HTML Code:

 <div ng-repeat="workshop in sunday_workshop">
                        <input type="checkbox" name="sun_workshop" ng-checked="workshop.flag" ng-model="workshop.flag" ng-click="workshop_method('sunday')"> {{workshop.WS_Option}}

Upvotes: 0

Ed_
Ed_

Reputation: 19098

You need the help of a controller..

I'd do something like this:

Initialise an empty array of values on the $scope and a function to use on change.

$scope.checkboxes = [];

$scope.alert = function(index, event){

  alert("checkbox " + index + " is " + $scope.checkbox[index]);

}

Bind ng-model to checkboxes[$index], then you can use ng-change because you have specified a model.

<input type="checkbox" 
       ng-model="checkbox[$index]" 
       ng-change="alert($index)"> 

See this plunker.

Upvotes: 5

Related Questions