Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular checkbox and ng-click

Tags:

angularjs

Angular 1.2:

<input type="checkbox" ng-model="vm.myChkModel" ng-click="vm.myClick(vm.myChkModel)"> 

I don't have the right state in my myClick function?

I want the state, after the click.

like image 723
daniel Avatar asked Nov 29 '13 17:11

daniel


People also ask

How to check checkbox on button click in Angular?

Approach: The approach is to use the ng-checked directive to check the checkbox in the DOM. In the first example, a single checkbox is checked by the button and In the second example, multiple checkboxes are checked by the button. The ng-model directive is used to bind the checkboxes.

How to set checkbox checked in Angular?

AngularJS ng-checked DirectiveThe ng-checked directive sets the checked attribute of a checkbox or a radiobutton. The checkbox, or radiobutton, will be checked if the expression inside the ng-checked attribute returns true. The ng-checked directive is necessary to be able to shift the value between true and false .

How to call a function when checkbox is checked in AngularJS?

You should call your method on ng-change of checkbox, to get correct changed value. Also add ng-model to get two way binding enable your checkbox value.


2 Answers

The order of execution of ng-click and ng-model is ambiguous since they do not define clear priorities. Instead you should use ng-change or a $watch on the $scope to ensure that you obtain the correct values of the model variable.

In your case, this should work:

<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)"> 
like image 106
musically_ut Avatar answered Nov 02 '22 10:11

musically_ut


You can use ng-change instead of ng-click:

<!doctype html> <html> <head>   <script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>   <script>         var app = angular.module('myapp', []);         app.controller('mainController', function($scope) {           $scope.vm = {};           $scope.vm.myClick = function($event) {                 alert($event);           }         });        </script>   </head> <body ng-app="myapp">   <div ng-controller="mainController">     <input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">   </div> </body> </html> 
like image 25
cardeol Avatar answered Nov 02 '22 09:11

cardeol