Angular - 将范围值保存到变量,但在范围更新时不更新它
Angular - save scope value to variable, but not update it when scope updates
我有这样的东西:
$scope.last_good_configuration = $scope.storage;
在 $scope.last_good_configuration 我保留了上次的正确设置。
当用户输入错误的值时,例如我想做的太大的整数:
$scope.storage = $scope.last_good_configuration;
但是我的$scope.last_good_configuration一直和$scope.storage一样。如何停止更新$scope.last_good_configuration?我必须以某种方式评估我的范围?
由于对象是通过引用传递的,你需要创建一个new对象来存储默认配置。否则,当你修改$scope.last_good_configuration
时,它也会影响$scope.storage
因为它们都指向同一个对象。
使用 angular.extend
方法将所有属性从 $scope.storage
复制到新对象 {}
:
$scope.last_good_configuration = angular.extend({}, $scope.storage);
更新。我完全忘记了专用 angular.copy
这在这种情况下可能更合适,尤其是 $scope.storage
具有嵌套对象结构:angualar.extend
将进行浅拷贝,在这种情况下你应该使用 angular.copy
(见 Satpal 回答)。
您可以使用 angular.copy()
创建一个新对象,这样当您对 storage
进行更改时,它不会影响 last_good_configuration
$scope.last_good_configuration = angular.copy($scope.storage);
您需要复制或克隆原始对象。 Angular 有一个内置方法:angular.copy.
$scope.last_good_configuration = angular.copy($scope.storage);
//Edits must be at least 6 characters workaround
我有这样的东西:
$scope.last_good_configuration = $scope.storage;
在 $scope.last_good_configuration 我保留了上次的正确设置。
当用户输入错误的值时,例如我想做的太大的整数:
$scope.storage = $scope.last_good_configuration;
但是我的$scope.last_good_configuration一直和$scope.storage一样。如何停止更新$scope.last_good_configuration?我必须以某种方式评估我的范围?
由于对象是通过引用传递的,你需要创建一个new对象来存储默认配置。否则,当你修改$scope.last_good_configuration
时,它也会影响$scope.storage
因为它们都指向同一个对象。
使用 angular.extend
方法将所有属性从 $scope.storage
复制到新对象 {}
:
$scope.last_good_configuration = angular.extend({}, $scope.storage);
更新。我完全忘记了专用 angular.copy
这在这种情况下可能更合适,尤其是 $scope.storage
具有嵌套对象结构:angualar.extend
将进行浅拷贝,在这种情况下你应该使用 angular.copy
(见 Satpal 回答)。
您可以使用 angular.copy()
创建一个新对象,这样当您对 storage
进行更改时,它不会影响 last_good_configuration
$scope.last_good_configuration = angular.copy($scope.storage);
您需要复制或克隆原始对象。 Angular 有一个内置方法:angular.copy.
$scope.last_good_configuration = angular.copy($scope.storage);
//Edits must be at least 6 characters workaround