Jazzy
Jazzy

Reputation: 6139

AngularJS unbind equivalent variables

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?

Upvotes: 6

Views: 2672

Answers (2)

Radim Köhler
Radim Köhler

Reputation: 123861

As discussed in the comments, 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

Upvotes: 6

haferje
haferje

Reputation: 1003

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.

Upvotes: 1

Related Questions