dimanche 28 juin 2015

"Cannot set property 'checked' of undefined" on ng-change of checkbox

I have an array of objects, each one has a couple variables which one of them is "checked" - a true or false whether a checkbox should be checked or not. When I load the page I pull the array of objects from the server and use ng-repeat to show the list of objects. Each object has a checkbox with ng-model="extReviewCheckbox[$index]" variable which is equal to the checked variable from the data retrieved from the server. Most of the time that works well, but once in few refreshes suddenly I get all the checkboxes unchecked, while the data from the server indicates otherwise, and when I try clicking on the checkbox nothing happens and I get the following error in the console:

TypeError: Cannot set property 'checked' of undefined
at sb (container_of_all_ext_scripts.js:formatted:4840)
at bb.fieldAccess.E.assign (container_of_all_ext_scripts.js:formatted:6839)
at Re.$setViewValue (container_of_all_ext_scripts.js:formatted:7111)
at container_of_all_ext_scripts.js:formatted:7050
at h.$get.h.$eval (container_of_all_ext_scripts.js:formatted:5329)
at h.$get.h.$apply (container_of_all_ext_scripts.js:formatted:5339)
at HTMLInputElement.<anonymous> (container_of_all_ext_scripts.js:formatted:7049)
at HTMLInputElement.v.event.dispatch (container_of_all_ext_scripts.js:formatted:1141)
at HTMLInputElement.v.event.add.o.handle.u (container_of_all_ext_scripts.js:formatted:1061)

all these lines point to native Angular code.

HTML (Wrapped in a div with ng-repeat):

<input value="{{review}}" ng-init="initExtReviewsCheckboxes($index)" ng-model="extReviewCheckbox[$index]" ng-change="addData(review,extReviewCheckbox[$index]) type="checkbox">

the ng-init function:

    $scope.initExtReviewsCheckboxes = function (idx) {
    if(typeof($scope.data.workunit_s) != 'undefined') {
            $scope.extReviewCheckbox[idx]  =  $scope.data.workunit_s[idx].checked == null ? true : $scope.data.workunit_s[idx].checked;
            console.log("idx is: " + idx + " checked? " + $scope.extReviewCheckbox[idx]);
    }
    else {
        setTimeout(function() {
            $scope.initExtReviewsCheckboxes(idx);
        },1000);
    }   
}

The weird thing is that even when I get the "checked" undefined error, I do see the console.logs - console.log("idx is: " + idx + " checked? " + $scope.extReviewCheckbox[idx]); which proves that my "checked" variable is defined.

What may cause this problem?

Thanks.




Aucun commentaire:

Enregistrer un commentaire