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.
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.
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 .
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.
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)">
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With