AngularJS checkbox ng-change issue with $event.target

佐手、 提交于 2019-12-18 03:15:11

问题


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>

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:

TypeError: Cannot read property 'target' of undefined

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.

Thank you very much!


回答1:


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

From an collaborator in AngularJS official github repo:

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.

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

How can you solve your requirement?

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}}

Controller

$scope.updateTotal = function(item_selected) {

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

UPDATED

You can test it here, in this plnkr



来源:https://stackoverflow.com/questions/29108858/angularjs-checkbox-ng-change-issue-with-event-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!