"无法设置属性'已检查'未定义"关于ng-change的复选框

时间:2015-06-28 12:45:56

标签: javascript angularjs checkbox angular-ngmodel ng-init

我有一个对象数组,每个对象都有一些变量,其中一个是"检查" - 是否应检查复选框的真或假。当我加载页面时,我从服务器中拉出对象数组并使用ng-repeat来显示对象列表。每个对象都有一个复选框,其中包含ng-model =" extReviewCheckbox [$ index]"变量,它等于从服务器检索的数据中的checked变量。 大部分时间都运行良好,但是一旦几次刷新突然我取消选中所有复选框,而来自服务器的数据另有说明,当我尝试点击复选框时没有任何反应,我在控制台中收到以下错误:

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)

所有这些行都指向原生的Angular代码。

HTML(用ng-repeat包含在div中):

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

ng-init功能:

    $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);
    }   
}

奇怪的是,即使我接受了检查&#34;未定义的错误,我确实看到了console.logs - console.log("idx is: " + idx + " checked? " + $scope.extReviewCheckbox[idx]);,它证明了我的&#34;检查了#34;变量已定义。

可能导致此问题的原因是什么?

感谢。

1 个答案:

答案 0 :(得分:0)

我认为这一行可能是个问题:

 $scope.extReviewCheckbox[idx]  =  $scope.data.workunit_s[idx].checked == null ? true : $scope.data.workunit_s[idx].checked;

您的'if'语句会检查:

typeof($scope.data.workunit_s) != 'undefined'

但它没有检查是否:

typeof($scope.data.workunit_s)[idx] != 'undefined'

看起来您的“$ scope.data.workunit_s”对象/数组存在,但数组/对象中的$ scope.data.workunit_s [idx]项未定义。

希望这有帮助!