Clicking a checkbox with ng-click does not update the model
Clicking on a checkbox and calling ng-click: the model is not updated before ng-click kicks in so the checkbox value is wrongly presented in the UI:
This works in AngularJS 1.0.7 and seems broken in Angualar 1.2-RCx.
<div ng-app="myApp" ng-controller="Ctrl">
<li ng-repeat="todo in todos">
<input type='checkbox' ng-click='onCompleteTodo(todo)' ng-model="todo.done">
{{todo.text}}
</li>
<hr>
task: {{todoText}}
<hr><h2>Wrong value</h2>
done: {{doneAfterClick}}
and controller:
angular.module('myApp', [])
.controller('Ctrl', ['$scope', function($scope) {
$scope.todos=[
{'text': "get milk",
'done': true
},
{'text': "get milk2",
'done': false
}
];
$scope.onCompleteTodo = function(todo) {
console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text);
$scope.doneAfterClick=todo.done;
$scope.todoText = todo.text;
};
}]);
Broken Fiddle w/ Angular 1.2 RCx - http://jsfiddle.net/supercobra/ekD3r/
Working fidddle w/ Angular 1.0.0 - http://jsfiddle.net/supercobra/8FQNw/
How about changing
<input type='checkbox' ng-click='onCompleteTodo(todo)' ng-model="todo.done">
to
<input type='checkbox' ng-change='onCompleteTodo(todo)' ng-model="todo.done">
From docs:
Evaluate given expression when user changes the input. The expression is not evaluated when the value change is coming from the model.
Note, this directive requires
ngModel
to be present.
As reported in https://github.com/angular/angular.js/issues/4765, switching from ng-click to ng-change seems to fix this (I am using Angular 1.2.14)
The order in which ng-click
and ng-model
will be executed is ambiguous (since neither explicitly set their priority
). The most stable solution to this would be to avoid using them on the same element.
Also, you probably do not want the behavior that the examples show; you want the checkbox
to respond to clicks on the complete label text, not only the checkbox. Hence, the cleanest solution would be to wrap the input
(with ng-model
) inside a label
(with ng-click
):
<label ng-click="onCompleteTodo(todo)">
<input type='checkbox' ng-model="todo.done">
{{todo.text}}
</label>
Working example: http://jsfiddle.net/b3NLH/1/