0

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?!

6
  • 1
    please provide a minimal reproducible example Commented Jun 24, 2016 at 11:57
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. Commented Jun 24, 2016 at 11:58
  • It looks that you want to bind $rootScope with input control but don't want to change it. Am I right? Commented Jun 24, 2016 at 12:01
  • @Pooja-G Yes! exactly Commented Jun 24, 2016 at 12:41
  • @MehdiGuelloub I think you got the answer.. use angular.copy() Commented Jun 24, 2016 at 12:48

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

if the currentUser is a deep object, he might need angular.merge
Why? It does not have to merge, only be copied over.
copy make a shallow copy, meaning, reference of subfields won't be clone, they will be kept as is. Merge perform a deep copy. As i said it's only if his currentUser object has more than one level.
0

Copy the user object

updatedUser = angular.copy(currentUser);

and use

ng-model="updatedUser"

which then is initialised with the old values

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.