0

Say I have some user data that's been loaded. That's now stored in a 'user' model that's within mainCtrl's scope. I'd then like an user update form that is initially populated with this user data, but only updates the 'user' model when the form has successfully been submitted.

I'm I going about this entirely wrong? I'm running in to difficulties with references being assigned, so the two models ('user' and 'updateUser') cannot be updated independently.

HTML

<div ng-controller="mainCtrl">
    <form ng-controller="updateCtrl" ng-submit='submit()'>
        <input ng-model='updateUser.firstName'>
        <input ng-model='updateUser.email'>
    </form>
</div>

JS

var userData = {
    'firstName': 'Chris',
    'email': 'test@test.com'
}

app.controller('mainCtrl', ['$scope', '$http',
    function($scope, $http) {
        $scope.user = userData;
    };
]);

app.controller('updateCtrl', ['$scope', '$http',
    function($scope, $http) {
        $scope.updateUser = $scope.user;

        $scope.submit = function () {
        // Submit form to server and on success, update $scope.user
        }
    };
]);
ChrisE
  • 35
  • 5

1 Answers1

0
$scope.updateUser = angular.copy($scope.user);

$scope.submit = function () {
    // Submit form to server and on success, update $scope.user
    ..
    ..
    $scope.user = angular.copy($scope.updateUser);
}
AlwaysALearner
  • 43,759
  • 9
  • 96
  • 78
  • Thank you, this is exactly what I needed. The only issue I'm having now is that instances of ng-model='user.firstName' are not updating elsewhere once it has successfully been updated. $scope.$apply() is giving me an 'already digesting' error. – ChrisE Mar 07 '14 at 12:21
  • I dont understand. You need to create a fiddle. – AlwaysALearner Mar 07 '14 at 12:25
  • Here we go: http://jsfiddle.net/Tenchu55/xYSL2/ The view isn't updated after the form submission. $scope.$apply() is giving an error. Checking the console, the model 'user' is being updated though. – ChrisE Mar 07 '14 at 12:36
  • `UpdateCtrl` creates a different scope which means a new `$scope.user` is created inside the child scope. To get around this issue, wrap your model inside an object. Here's the updated fiddle: http://jsfiddle.net/xYSL2/1/ – AlwaysALearner Mar 07 '14 at 12:41
  • I have to be honest, I don't understand the difference! But I've taken enough of your time, so thank you so much. I would upvote you but I don't have the reputation. I will when I can... – ChrisE Mar 07 '14 at 12:58
  • Ahhh, wait - I think I do. This is essentially this - http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs It was creating a new object, rather than looking to the parent for it. But what you've done is update the property, which it searches the parent for, rather than it creating a new object. – ChrisE Mar 07 '14 at 13:02