Angular 1.2:
<input type="checkbox" ng-model="vm.myChkModel" ng-click="vm.myClick(vm.myChkModel)">
我的myClick
函数中没有正确的状态?
点击后我想要状态。
答案 0 :(得分:89)
ng-click
和ng-model
的执行顺序不明确,因为它们没有明确优先级。相反,您应该使用ng-change
上的$watch
或$scope
来确保您获得模型变量的正确值。
在您的情况下,这应该有效:
<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
答案 1 :(得分:21)
您可以使用ng-change而不是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>
答案 2 :(得分:8)
https://jsfiddle.net/vtL5x0wh/
代码:
<body ng-app="checkboxExample">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.value0 = "none";
$scope.value1 = "none";
$scope.value2 = "none";
$scope.value3 = "none";
$scope.checkboxModel = {
critical1: {selected: true, id: 'C1', error:'critical' , score:20},
critical2: {selected: false, id: 'C2', error:'critical' , score:30},
critical3: {selected: false, id: 'C3', error:'critical' , score:40},
myClick : function($event) {
$scope.value0 = $event.selected;
$scope.value1 = $event.id;
$scope.value2 = $event.error;
$scope.value3 = $event.score;
}
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>
Value1:
<input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
</label><br/>
<label>Value2:
<input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
</label><br/>
<label>Value3:
<input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
</label><br/><br/><br/><br/>
<tt>selected = {{value0}}</tt><br/>
<tt>id = {{value1}}</tt><br/>
<tt>error = {{value2}}</tt><br/>
<tt>score = {{value3}}</tt><br/>
</form>
答案 3 :(得分:1)
ng-click和ng-model的执行顺序与angular 1.2 vs 1.6
不同您必须使用1.2和1.6进行测试
例如,使用角度1.2,ng-click在ng-model之前执行, 使用角度1.6,ng-model可能会在ng-click之前执行。
所以你得到了真正的检查&#39; /&#39; false取消选中&#39;价值也许不是你期望的