<style>
ul { list-style: none; }
label { float: left; margin-right: 30px; }
</style>
<div ng-controller="ctrl">
<div ng-if="!isEdit">
<span class="icon-edit" ng-click="whetherEdit()">edit</span>
<ul>
<li ng-repeat="item in items">
<label>{{item.title}}</label>
<span>{{item.value}}</span>
</li>
</ul>
</div>
<form ng-if="isEdit">
<ul>
<li ng-repeat="item in items">
<label>{{item.title}}</label>
<input type="text" ng-model="tempValues[$index]">
</li>
</ul>
<input type="button" value="取消" ng-click="whetherEdit()">
<input type="submit" value="提交" ng-click ="submitForm()">
</form>
</div>
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 <anonymous> (angular.js:13322), <anonymous>:4:221)
at callback (angular.js:23549)
at Scope.$eval (angular.js:15989)
at Scope.$apply (angular.js:16089)
at HTMLInputElement.<anonymous> (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
也已经发生了变化,只是因为报错页面没有回到信息展示部分(仍在编辑页面)。
自己又折腾了一下,找到原因了,在getTempValues()中,没有对$scope.tempValues进行清空,使数组在不断地变长,最终其长度大于$scope.items的长度,导致后面赋值失败。