冯奕轩 冯奕轩 - 4 months ago 51
AngularJS Question

ng-change does not trigger when the checkbox is already checked

Here is the background:the checkbox was checked when "isChecked == 1" while its initalization,however,it doesn't trigger the "ng-change" event in its first "click" action.

<td ng-repeat="isCheck in item.check track by $index">
<input type="checkbox" ng-model="isCheck" ng-checked="isCheck == 1" ng-true-value="1" ng-false-value="0" ng-change="f(isCheck, item, vm.modules[$index])"/>
</td>

Answer

I created a working JSFidlle that perfectly triggers the function called by ng-change.

JS:

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.item = {};
    $scope.item.check = [1, 0, 1, 0];

    $scope.f = function(isCheck, item, modules) {
        console.log(isCheck);
    };
});

HTML:

<div ng-controller="MyCtrl">
    <table>
        <tr>
            <td ng-repeat="isCheck in item.check track by $index">
                <input type="checkbox" ng-model="isCheck" ng-checked="isCheck == 1" ng-true-value="1" ng-false-value="0" ng-change="f(isCheck, item, vm.modules[$index])"/>
            </td>
        </tr>
    </table>
</div>