Javascript $event.target 的 AngularJS 复选框 ng-change 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29108858/
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
AngularJS checkbox ng-change issue with $event.target
提问by Philip Tenn
I'm writing a simple AngularJS Controller that keeps track of the number of checkboxes checked. Trying to avoid $scope.$watchand instead use ng-changeto increment/decrement the total count.
我正在编写一个简单的 AngularJS 控制器,用于跟踪选中的复选框数量。试图避免$scope.$watch并改为使用ng-change增加/减少总计数。
HTML:
HTML:
<form ng-controller="MainCtrl">
<table>
<tr ng-repeat="item in data">
<td>
<input type="checkbox"
value="{{item.id}}"
ng-model="item.selected"
ng-change="updateTotal($event)"> {{item.name}}
</td>
</tr>
</table>
<p>
Total checked: {{totalSelected}}
</p>
</form>
Controller snippet
控制器片段
$scope.updateTotal = function($event) {
var checkbox = $event.target;
if (checkbox.checked) {
$scope.totalSelected++;
}
else {
$scope.totalSelected--;
}
}
I keep getting an error in the controller where I attempt to access $event.target:
我在尝试访问的控制器中不断收到错误消息$event.target:
TypeError: Cannot read property 'target' of undefined
I created a Plunk for recreating: http://plnkr.co/edit/qPzETejmMHHZCQ2sV2Sk?p=info
我创建了一个用于重新创建的 Plunk:http://plnkr.co/edit/qPzETejmMHHZCQ2sV2Sk?p=info
If anyone has any ideas or suggestions I would be very grateful.
如果有人有任何想法或建议,我将不胜感激。
Thank you very much!
非常感谢!
回答by levi
ng-changefunction doesn't allow to pass $eventas variable.
ng-change函数不允许$event作为变量传递。
From an collaborator in AngularJS official github repo:
来自 AngularJS 官方 github 存储库的合作者:
ng-change is not a directive for handling the change event (I realize that this is confusing given the name), but is actually instead notified when ngModelController.$setViewValue() is called and the value changes (because ng-change adds a listener to the $viewChangeListeners collection). So this is as expected.
ng-change 不是用于处理 change 事件的指令(我意识到这名称令人困惑),但实际上是在调用 ngModelController.$setViewValue() 并且值发生变化时得到通知(因为 ng-change 添加了一个侦听器到 $viewChangeListeners 集合)。所以这正如预期的那样。
You can read more about it ng-change doesn't get the $event argument
你可以阅读更多关于它ng-change 没有得到 $event 参数
How can you solve your requirement?
您如何解决您的需求?
Just pass item.selectedto your ng-change function and check its value.
只需传递item.selected给您的 ng-change 函数并检查其值。
HTML
HTML
<input type="checkbox"
value="{{item.id}}"
ng-model="item.selected"
ng-change="updateTotal(item.selected)"> {{item.name}}
Controller
控制器
$scope.updateTotal = function(item_selected) {
if (item_selected) {
$scope.totalSelected++;
}
else {
$scope.totalSelected--;
}
}
UPDATED
更新
You can test it here, in this plnkr
你可以在这里测试它,在这个plnkr

