AngularJS checkbox ng-change issue with $event.target

后端 未结 1 1020
说谎
说谎 2020-12-15 23:01

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<

相关标签:
1条回答
  • 2020-12-15 23:57

    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

    0 讨论(0)
提交回复
热议问题