javascript - AngularJS unbind equivalent variables - Stack Overflow

Working on a form for a user to edit their details based on a variable on the $rootScope (could also be

Working on a form for a user to edit their details based on a variable on the $rootScope (could also be $scope).

$rootScope.formData = $rootScope.user;

In the view, there is an ng-model on the input:

 ng-model="formData.email"

The behavior I expect is to update the model and only $rootScope.formData will update, but instead, both update.

Is there a way to break the relationship between the two?

Working on a form for a user to edit their details based on a variable on the $rootScope (could also be $scope).

$rootScope.formData = $rootScope.user;

In the view, there is an ng-model on the input:

 ng-model="formData.email"

The behavior I expect is to update the model and only $rootScope.formData will update, but instead, both update.

Is there a way to break the relationship between the two?

Share Improve this question asked Jan 12, 2014 at 5:29 JazzyJazzy 6,15911 gold badges54 silver badges75 bronze badges 2
  • The expectation here is wrong. user is a reference. Objects in JS are passed as reference. That's it. You can always call clone or cloneDeep (e.g. lo-dash). I would suggest rethink your design based on the fact, that JS behaviour is passing by reference – Radim Köhler Commented Jan 12, 2014 at 5:49
  • You are right and the docs give this exact scenario as the example for angular.copy(). If you make this the answer I will mark it as such. All I had to do was wrap the second var in that method. Thanks. docs.angularjs/api/angular.copy – Jazzy Commented Jan 12, 2014 at 5:53
Add a ment  | 

2 Answers 2

Reset to default 6

As discussed in the ments, we are working with JS references. That means, that we are passing the user as reference to the other (root) scope

We can call angular.copy() or cloneDeep() (see lo-dash) to work with a new instance

The problem is that you have set one object to another. Objects are passed by reference in Javascript, so you essentially made $rootScope.formData a pointer to $rootScope.user. This is why updating one updates the other.

You could $rootScope.user = null;, which would essentially remove the reference, but you have then lost the reference that it had in the first place. If that is unwanted, I guess you could clone the user object into formData, which can be a feat in itself if you don't have a library that provides this capability.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744722737a4590006.html

相关推荐

  • javascript - AngularJS unbind equivalent variables - Stack Overflow

    Working on a form for a user to edit their details based on a variable on the $rootScope (could also be

    19小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信