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?
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?
Share Improve this question edited Mar 11, 2014 at 10:18 aadu asked Mar 11, 2014 at 10:12 aaduaadu 3,25410 gold badges42 silver badges65 bronze badges 3- Can you add jsfiddle? – JQuery Guru 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? – aadu Commented Mar 11, 2014 at 10:19
- 1 have a look at this answer – ms87 Commented Mar 11, 2014 at 10:20
2 Answers
Reset to default 5You 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.
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}}