I have a one-page application using angularJS. I have in my controller a user object defined like this :
this.user = {
'name':'Robert',
'age':'30'
}
I made a form to update those informations prefilled with those user's informations on my page such like this :
<form name="userForm" ng-submit="userForm.$valid && pageCtrl.userForm(user)" novalidate>
<label for="name">Name *</label>
<input type="text" name="name" ng-model='pageCtrl.user.name' class="form-control" required/>
<label for="age">Age *</label>
<input type="text" name="age" ng-model='pageCtrl.user.age' class="form-control" required/>
<span ng-if='!userForm.$valid' class="error">Invalid form</span>
<input type="submit" value="Save my informations" class="btn btn-success"/>
</form>
My problem is the following : in the header bar of the page the username is displayed ({{pageCtrl.user.name}}). When the user acts on the form by changing his name, this is updating before the form is saved. I'd like to wait for the form submission to see the username updated. But i still want to get my form prefilled with user's informations.
Do you have any idea about how to do this?
Thank you by advance
You can use a copied object to only apply the changes when the user save the form :
var app = angular.module('app', []);
app.controller('pageCtrl', function() {
var vm = this;
vm.user = {
'name':'Robert',
'age':'30'
};
vm.tmpUser = {};
vm.update = function() {
vm.user = angular.copy(vm.tmpUser);
};
vm.reset = function() {
vm.tmpUser = angular.copy(vm.user);
};
vm.reset();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="pageCtrl as pageCtrl">
<form name="userForm" ng-submit="userForm.$valid" novalidate>
<label for="name">Name *</label>
<input type="text" name="name" ng-model='pageCtrl.tmpUser.name' class="form-control" required/>
<label for="age">Age *</label>
<input type="text" name="age" ng-model='pageCtrl.tmpUser.age' class="form-control" required/>
<span ng-if='!userForm.$valid' class="error">Invalid form</span>
<input type="submit" ng-click="pageCtrl.update()" ng-disabled="!userForm.$valid" value="Save my informations" class="btn btn-success" />
</form>
<pre>user = {{pageCtrl.user | json}}</pre>
<pre>tmpUser = {{pageCtrl.tmpUser | json}}</pre>
</body>