0

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?

3
  • Can you add jsfiddle? Commented Mar 11, 2014 at 10:15
  • I can't really add a fiddle because I don't know how to do this properly. The fiddle would just be broken. Is something not clear? Commented Mar 11, 2014 at 10:19
  • 1
    have a look at this answer Commented Mar 11, 2014 at 10:20

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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}}

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.