Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 909
supercobra Avatar asked Oct 21 '13 14:10

supercobra


People also ask

What is the difference between click and Ng-click?

Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.

Can we use NG-click and Onclick together?

For a single btn, it's ok to use ng-click or onclick in the ng-app . There is no difference between the two functions. For effective team work, you,d better to have an account with each other. In Angular apps, ng-click is recommended.

What is the use of NG-click?

The ng-click directive tells AngularJS what to do when an HTML element is clicked.

What is NG model and Ng change?

Ng-change is a directive in AngularJS which is meant for performing operations when a component value or event is changed. In other words, ng-change directive tells AngularJS what to do when the value of an HTML element changes. An ng-model directive is required by the ng-change directive.


1 Answers

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.

like image 199
kakoni Avatar answered Sep 22 '22 07:09

kakoni