Reputation: 368
I have user data fetched from database and stored into my $rootScope.currentUser
I want to pass those data to the update-form so the user can see old values an update them.
I want that the users' updates does not affect my $rootScope.currentUser
so I can keep old values
I tried to achieve that throught 2 solutions:
1) Using ng-model="currentUser.name"
...
=> Thats affect the $rootScope, every change in the form change automatically $rootScope values
2) Using ng-values="currentUser.name"
and ng-model="updatedUser.name"
on the same input
=> Thats does not affect the $rootScope BUT the form validation is considering the form as empty since updatedUser(the model) doesn't have a default value onload !!
(Also ng-value doesn't work with textArea !! I don't know why!)
So, anyway, what is the best solution to achieve that?!
Upvotes: 0
Views: 2890
Reputation: 13997
When you retrieve the existing user, just do something like this in your controller that controls the edit:
function myController($scope, $rootScope) {
// make a copy of the current user
$scope.editUser = angular.copy($rootScope.currentUser);
$scope.save = function() {
// save copy of edited in rootscope
$rootScope.currentUser = angular.copy($scope.editUser);
}
}
Then in your form:
<form ng-controller="myController">
<input type="text"
ng-model="editUser.name" />
<button type="button"
ng-click="save()">Save</button>
</form>
See also this jsfiddle
Upvotes: 2
Reputation: 91
Copy the user object
updatedUser = angular.copy(currentUser);
and use
ng-model="updatedUser"
which then is initialised with the old values
Upvotes: 0