javascript - 作用域内赋值时出现 TypeError: Cannot read property 'value' of undefined
高洛峰
高洛峰 2017-04-11 09:05:39
[JavaScript讨论组]


edit

  • {{item.value}}

function ctrl($scope) { 'ngInject'; $scope.items = [ { title: "item1", value: "value1" },{ title: "item2", value: "value2" },{ title: "item3", value: "value3" } ]; $scope.tempValues = []; var getTempValues = function() { for(var i=0;i<$scope.items.length;i++) { $scope.tempValues.push($scope.items[i].value); } }; $scope.isEdit = false; $scope.whetherEdit = function(){ $scope.isEdit = !$scope.isEdit; if($scope.isEdit === true) { getTempValues(); } } $scope.submitForm = function(){ for(var j=0;j<$scope.tempValues.length;j++) { console.log($scope.items[j].value); $scope.items[j].value = $scope.tempValues[j]; } $scope.isEdit = !$scope.isEdit; } }

当点击提交按钮后,报错如下:

angular.js:12477 TypeError: Cannot read property 'value' of undefined
    at Scope.$scope.submitForm (setting-viewer.controller.js:65)
    at fn (eval at  (angular.js:13322), :4:221)
    at callback (angular.js:23549)
    at Scope.$eval (angular.js:15989)
    at Scope.$apply (angular.js:16089)
    at HTMLInputElement. (angular.js:23554)
    at HTMLInputElement.jQuery.event.dispatch (jquery.js:4435)
    at HTMLInputElement.elemData.handle (jquery.js:4121)(anonymous function) @ angular.js:12477(anonymous function) @ angular.js:9246Scope.$apply @ angular.js:16094(anonymous function) @ angular.js:23554jQuery.event.dispatch @ jquery.js:4435elemData.handle @ jquery.js:4121

求问:submitForm()中,console能够打出$scope.items[i].value;但是当第二次提交时,为什么$scope.items[i].value = $scope.tempValues[i];就报错了呢?并且实际上$scope.items[i].value也已经发生了变化,只是因为报错页面没有回到信息展示部分(仍在编辑页面)。

plunker 展示请戳这里

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
天蓬老师

自己又折腾了一下,找到原因了,在getTempValues()中,没有对$scope.tempValues进行清空,使数组在不断地变长,最终其长度大于$scope.items的长度,导致后面赋值失败。

高洛峰

对 angular.js 一窍不通,
但是这一句

 $scope.tempValues.push($scope.settingItems[i].value);
 
 

不应该是

 $scope.tempValues.push($scope.settingItems[i]);
 

不然不是相当于取了 value.value了,没看到你的settingItems定义在哪里

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号