AngularJS Checkbox not working
You are trying to force too complex solution. To start with, you do not need ng-checked
nor ng-change
when you are using ng-model
.
Let's say you have the following controller
app.controller('MainCtrl', function($scope) {
$scope.case = {
caseId: 0,
steps: [
{ id: 1, name: 'First step', enabled: true },
{ id: 2, name: 'Second step', enabled: false },
{ id: 2, name: 'Third step', enabled: false }]
};
});
And related HTML
<div ng-repeat="step in case.steps">
<input type="checkbox" ng-model="step.enabled"> {{ step.name }}
</div>
That's all it takes!
Example Plunk here http://plnkr.co/edit/QjD91l
Edit:
If you need to do some processing based on selection, then yes, you could add ng-change
to input
control. Then HTML becomes
<input type="checkbox" ng-model="step.enabled" ng-change="stateChanged(step)"> {{ step.name }}
And in controller
$scope.stateChanged = function(step){
console.log('Changed step id:' + step.id + ' enabled state to ' + step.enabled;
};
I had to abandon ng-model for my checkbox as it was not picking up the initial value that was set in the model (in response to a service call). All of the other input controls were responding correctly to the model (and, interestingly, were correctly enabled/disabled based on the value backing the checkbox).
Instead, I used the 'checked' attibute and ng-click, as so:
<input type="text" ng-disabled="!myModel.isFruit" ng-model="myModel.seedCount">
<input type="checkbox" checked="{{myModel.isFruit}}" ng-click="onFruitClicked()"> Is Fruit
In my controller:
$scope.myModel = {
isFruit : myServices.getIsFruit(),
seedCount : myServices.getSeedCount()
};
$scope.onFruitClicked = function() {
// toggle the value
$scope.myModel.isFruit = !$scope.myModel.isFruit;
// save the new value
myServices.setIsFruit($scope.myModel.isFruit);
};