Javascript 检测是否在angularjs ng-change事件中选中或取消选中复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27411826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:07:30  来源:igfitidea点击:

detect if checkbox is checked or unchecked in angularjs ng-change event

javascriptjqueryangularjscheckboxangularjs-scope

提问by Laziale

I want to detect if a checkbox has been checked or unchecked when a click is happening on the checkbox.

我想在复选框上发生单击时检测复选框是否已选中或未选中。

This is what I have:

这就是我所拥有的:

<input type="checkbox" ng-model="answers[item.questID]" ng-change="stateChanged()" />

And then in the controller I have:

然后在控制器中我有:

$scope.stateChanged = function () {
    alert('test');
}

I'm able to fire the alert when I do check/uncheck but how can I detect the state of the checkbox? I did research a bit to find a similar issue but I wasn't able to get what I need.

我可以在选中/取消选中时触发警报,但如何检测复选框的状态?我做了一些研究以找到类似的问题,但我无法得到我需要的东西。

Thanks, Laziale

谢谢,拉齐亚莱

回答by PSL

You could just use the bound ng-model(answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

您可以在 ng-change 方法中使用 bound ng-model( answers[item.questID]) 值本身来检测它是否已被检查。

Example:-

例子:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}

回答by Brennan

The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]

复选框的状态将反映在您绑定到的任何模型上,在这种情况下, $scope.answers[item.questID]