我有一个bootstrap模式。在按下close按钮时,数组的值正在改变,但它不应该改变。
controller.js
$scope.open = function(){
var modalInstance = $modal.open({
animation: true,
templateUrl: 'views/view1.html',
controller: 'controller2',
resolve: {
items: function(){
return $scope.array;
}
}
});
modalInstance.result.then(function (changed_array){
$scope.array = changed_array;
},function(){
// no change
});
};第二个控制器的代码
angular.module('storagewebApp').controller('controller2',function($scope, $modalInstance, items) {
$scope.array = items;
$scope.ok = function(){
$modalInstance.close($scope.array);
};
$scope.cancel = function(){
$modalInstance.dismiss('cancel');
};});
view2.html
<div class="modal-header">
<h4 class="modal-title">Set threshold</h4>
</div>
<div class="modal-body">
<div class="form-group" align="left">
<div> E:</div> <input type="text" ng-model="array[0]">
<div> M:</div><input type="text" ng-model="array[1]">
<div>T:</div><input type="text" ng-model="array[2]">
<div>F: </div><input type="text" ng-model="array[3]">
<div> I:</div><input type="text" ng-model="array[4]">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" ng-click="cancel()">Close</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Save</button>
</div>
</div>值通过输入框更改,但按关闭按钮时,值不应发送到第一个控制器,但单击关闭按钮时,更改后的数组的值将传递给第一个控制器。
发布于 2015-06-16 20:19:55
这是一个常见的AngularJS/JavaScript错误。当您实例化您的模态控制器时,您正在传递数组的引用。然后,在你的模态控制器中,你可以操作这个引用,即使你不把它传递回去。
当你写的时候:
$scope.array = items在内存中发生的情况是,$scope.arra_y指向与_items相同的位置。当您以任何方式修改$ items e.array的对象时,您也在修改项目。
作为一种解决方案,您需要将初始数组深度复制到新数组中,以这种方式创建新的对象和引用。AngularJS有一个内置的函数可以做到这一点:https://docs.angularjs.org/api/ng/function/angular.copy
angular.copy请参阅此选项,例如:http://plnkr.co/edit/W6EYUwQ1K1YAnfnJ2r4a?p=preview
发布于 2015-06-16 20:15:22
应该为模式窗口创建一个新的作用域。如下所示:
var modalScope = angular.extend(
$scope.$new(), {
val1ToPassToModal: $scope.originalValue1,
val2ToPassToModal: $scope.originalValue2,
});
$modal.open({
templateUrl: '…',
controller: '…',
scope: modalScope,
resolve: {
…
}
});当然,如果您不想将新值传递给模式窗口,您可以只编写:
scope: $scope.$new()。
https://stackoverflow.com/questions/30866855
复制相似问题