AngularJS - How to keep the original value if I didn't hit submit

I have a list of users on the left with details on the right. Correct parts are machined using shape and ng model inputs. So when I click on the user on the left, I change the selected user and the model automatically shows me the correct data on the right.

I also have a submit button that saves the changes to the server.

Everything works well, but the problem is that if I, for example, change the username, click on a different user and then go back to the first user, I see the changed name, but the information was never saved to the server. Thus, the client might think that the information was changed on the server when it was not. After I click refresh, I will return the old server values.

So how can I revert the changes to the model if I switch the model before hitting save?

By the way, I use ng-model

instead of using {{ }}

in value field because AngularJS validators don't work unless you use ng-model

thank

+3


source to share


2 answers


Each user selects an item on the left, copies the selected object into a new variable. You can copy using angular.copy function. Then show that the new variable is on the right side of the form. At the moment, the changes are "saved" because you are referencing elements in your array (so when you change something in the form, it changes to that element in the array). If you have a new variable for selectedItem, you won't have this problem anymore.



+3


source


I suggest bind the object to form input fields and use ng-submit to call a function to update your values ​​on the server, as Nemanja suggested.

I went ahead and made a simple JS Fiddle , so you have a small example to structure your code. Hope this helps!

HTML:



<form ng-model="data" ng-submit="simple.saveName()">
  Name: {{ simple.data.name }}
  <br />Twitter: {{ simple.data.twitter }}
  <br />
  <br />New name:
  <input type="text" ng-model="simple.newName" />
  <br />
  <button>Submit</button>
</form>

      

JavaScript:

(function () {
    angular
        .module('app', [])
        .controller('simpleController', SimpleController);

    function SimpleController() {
        var vm = this;

        // Public stuff.
        vm.data = {
            name: 'Joe',
            twitter: '@martellaj'
        };
        vm.newName;
        vm.saveName = saveName;

        // Private stuff.
        function saveName() {
            console.log('Saving name...');
            vm.data.name = vm.newName;
        };
    };
})();

      

+1


source







All Articles