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() {
$http({
method: 'POST',
url: API + '/api/Educations/UserEducations',
data: {}
}).then(function successCallback(response) {
vm.UserData = response.data;
vm.CachedUserData = response.data;
})
}
And here is my html:
<div ng-repeat="education in editEducationsCtrl.UserData">
<div>{{education.SchoolName}}</div>
<input type="text" ng-model="education.SchoolName">
<button ng-click="editEducationsCtrl.saveChanges()">Save</button>
<button ng-click="editEducationsCtrl.cancelChanges()">Cancel</button>
</div>
When user clicked cancel button, I want to write html cached data. But, 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 = response.data;
vm.CachedUserData = angular.copy(response.data);