Siva
Siva

Reputation: 1133

How to preserve an object initial data?

I am facing some weird behavior with AngularJS in preserving a variable data which got binded to a from using scope, let me explain my scenario.

I have a form whose field values are initially served form controller through a scope variable, I need to compare the updated values with those initial values while saving, so I kept the initial data in a variable and assigned that variable to scope.

Whenever I change the form fields, controller variable data also getting updated along with scope variable. I am not sure whether this is the correct behavior or not, I guess only scope should get updated.

Anyone please suggest the correct behavior and how to solve this issue if that's the correct behavior.

JS Bin: http://jsbin.com/kakapinuhe/edit?html,js,console,output

You will get to know the problem easily by looking at the above JSBin link, let me know if needed any clarification.

Thanks,
Siva

Upvotes: 0

Views: 100

Answers (2)

Siddharth
Siddharth

Reputation: 7166

Use angular.copy

Reason: When you write

$scope.formData = initData.

You are creating a reference to same object initData. So any changes in $scope.formData will reflect in object too. Using angular.copy will create a deep copy of source without any references.

Upvotes: 2

Abdel Raoof Olakara
Abdel Raoof Olakara

Reputation: 19353

Yes, that is the expected behavior of javascript. When you assign:

$scope.formData = initData;

you are NOT making a copy of your initData variable. Instead, your formData is refering to same memory space as your initData. in short, they are referring to the same data.. so even if formData change.. your initData is lost.

You can fix this by using angular.copy():

$scope.formData = angular.copy(initData);

Here is the modified JSbin: http://jsbin.com/yoviyesero/edit?html,js,console,output

Upvotes: 2

Related Questions