什么是angular.copy的好处? [英] What is the benefit of angular.copy?

查看:306
本文介绍了什么是angular.copy的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用angular.copy在某些情况下,像复制模型默认值的形式模型,是这样的:

I use angular.copy in some cases, like copying model default values to the form model, like this:

var customerModel = {
  name: '',
  point: 0
};

$scope.customer = angular.copy(customerModel);

function save() {
  //... Reset $scope.customer after success submit
  $scope.customer = angular.copy(customerModel);
}

...以prevent默认customerModel改变。

... to prevent the default customerModel changed.

我在一些codeS使用angular.copy空对象,或者阵列上找到。为什么他们不直接向变量分配空对象?

I found in some codes used angular.copy on empty object or array. Why they don't assign empty object directly to the variable?

$scope.customer = {}; // or [] for array

如果你空对象,或者阵列上使用复制,你能解释一下什么好处?

If you use copy on empty object or array, could you explain the benefit?

还有一个问题,你是怎么做的Ajax响应?复制或直接分配到一个变量?

And one more question, what did you do to ajax response? copy or assign it directly to a variable?

$http
  .get('example.com/api/v1/get/customer/1')
  .success(function(response) {
    $scope.customer = angular.copy(response.data);
    // or do you use $scope.customer = response.data ?
  })
;

如果你使用复制,你怎么想发生在响应对象?
难道是留在记忆里?或自动删除?

And if you used copy, what do you think happened to the response object? Is it remain in the memory? or deleted automatically?

推荐答案

您修改它复制对象prevent其他code。 (原来的对象可能会改变,但你的副本将不会看到的变化)

You copy an object to prevent other code from modifying it. (original object might change, but your copy won't see the changes)

如果你做到这一点:

 $scope.customer = customerModel

......以及一些回调/服务/诸如此类的东西改变了 customerModel ,你的范围将反映这一变化。这并不总是理想的,因此需要进行深度复制

... and some callback/service/whatnot changed customerModel, your scope would reflect this change. This is not always desirable, hence the need for deep copying.

$scope.customer = angular.copy({})
// or
$scope.customer = {}

这没有任何区别。这是每一次一个新的空对象。请注意,这是非常不同的:

This doesn't make any difference. It's a new empty object every time. Note that it's very different from this:

this.customerModel = {};
$scope.customer = angular.copy(this.customerModel)

复制Ajax响应数据

规则同样适用。如果你想确保这个对象不是由你改变底下(,这可能会发生,如果你还递给其他地方为例),你应该把它复制。

Copying ajax response data

Same rules apply. If you want to ensure that this object doesn't change from underneath you (which may happen if you also passed it to somewhere else, for example), you should copy it.

这篇关于什么是angular.copy的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆