Sam Sam - 4 months ago 4
AngularJS Question

Why angularjs change variables that are different?

I am getting an ajax data from api and saving it to a variable. And I have to "edit and save" or "edit and cancel" changes on this data. I am using ng-model to show and edit this data.

Here is my script:

function getData() {
method: 'POST',
url: API + '/api/Educations/UserEducations',
data: {}
}).then(function successCallback(response) {
vm.UserData =;
vm.CachedUserData =;

And here is my html:

<div ng-repeat="education in editEducationsCtrl.UserData">
<input type="text" ng-model="education.SchoolName">

<button ng-click="editEducationsCtrl.saveChanges()">Save</button>
<button ng-click="editEducationsCtrl.cancelChanges()">Cancel</button>

When user clicked cancel button, I want to write html cached data.
When I try to access vm.CachedUserData variable, I am seeing this cached data has already changed with new value of vm.UserData... How? I have checked my code there is no function access CachedUserData variable. Even I changed variable name to unique name but result is same.

I want to save first data in a variable. But angular changes both of them. Is 2 way databinding change all variables that connected the same ajax data?


I recommend you to use angular.copy() to bind the data you want to cache:

vm.UserData =;
vm.CachedUserData = angular.copy(;