使用$ event.target的AngularJS复选框更改问题 [英] AngularJS checkbox ng-change issue with $event.target

查看:276
本文介绍了使用$ event.target的AngularJS复选框更改问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的AngularJS控制器,用于跟踪所选复选框的数量。试图避免 $ scope。$ watch 而是使用 ng-change 来增加/减少总计数。

I'm writing a simple AngularJS Controller that keeps track of the number of checkboxes checked. Trying to avoid $scope.$watch and instead use ng-change to increment/decrement the total count.

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)"> &nbsp; {{item.name}}
       </td>
    </tr>
  </table>
  <p>
      Total checked: {{totalSelected}}
   </p>
</form>

控制器代码段

$scope.updateTotal = function($event) {

    var checkbox = $event.target;

    if (checkbox.checked) {
      $scope.totalSelected++;
    }
    else {
      $scope.totalSelected--;
    } 
}

我一直在我尝试的控制器中出错访问 $ event.target

I keep getting an error in the controller where I attempt to access $event.target:

TypeError: Cannot read property 'target' of undefined

我创建了一个用于重新创建的Plunk:http://plnkr.co/edit/qPzETejmMHHZCQ2sV2Sk?p=info

I created a Plunk for recreating: http://plnkr.co/edit/qPzETejmMHHZCQ2sV2Sk?p=info

如果有人有任何想法或建议,我将非常感激。

If anyone has any ideas or suggestions I would be very grateful.

非常感谢!

推荐答案

ng-change 函数不允许传递 $ event 作为变量。

ng-change function doesn't allow to pass $event as variable.

来自AngularJS的合作者官方github回购:

From an collaborator in AngularJS official github repo:


ng-change is不是处理更改事件的指令(我意识到
这个名称令人困惑),但实际上是在ngModelController时通知
。调用$ setViewValue()并且
值更改(因为ng-change为
$ viewChangeListeners集合添加了一个监听器)。所以这是预期的。

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未获得$ event参数

You can read more about it ng-change doesn't get the $event argument

您如何解决您的要求?

只需将 item.selected 传递给ng-change函数并检查其值。

Just pass item.selected to your ng-change function and check its value.

HTML

  <input type="checkbox" 
         value="{{item.id}}"
         ng-model="item.selected"
         ng-change="updateTotal(item.selected)"> &nbsp; {{item.name}}

控制器

$scope.updateTotal = function(item_selected) {

    if (item_selected) {
      $scope.totalSelected++;
    }
    else {
      $scope.totalSelected--;
    } 
}

更新

您可以在此 plnkr 中进行测试

You can test it here, in this plnkr

这篇关于使用$ event.target的AngularJS复选框更改问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆