Alex Man
Alex Man

Reputation: 4886

value is changing before save- angular js

i've created an application in angular js, in which i'm getting a json from a factory, upon which it is taken in two controllers Ctrl1 and Ctrl2. The code is working fine but in the structure i've cancel and save button in which when i cancel i need to redo the previous saved changes and when i click save it should update the json.

But since angular is two way binding, the value is getting change even before clicking the save button

My code is as given below

html

<div ng-app="app">
    <div ng-controller="Ctrl1">
        <form>
            <br></br>{{user}}</form>
    </div>
    <div ng-controller="Ctrl2">
        <input type="text" ng-model="user.name" /><br>
        <input type="button" ng-click="save()" value="Save" />
        <input type="button" ng-click="cancel()" value="Cancel" />
    </div>
</div>

script

var app = angular.module("app", []);
app.factory('InitApp', function () {
    return {
        name: 'Manu',
        age: 15
    };
});
app.controller('Ctrl1', function ($scope, InitApp) {
    $scope.user = InitApp;
});

app.controller('Ctrl2', function ($scope, InitApp) {
    $scope.user = InitApp;
    $scope.save = function () {

    }
    $scope.cancel = function () {}
});

Upvotes: 0

Views: 999

Answers (3)

Ben Felda
Ben Felda

Reputation: 1484

I am guessing that the changing value before hitting save is not desired. What you want to do is copy the object in your controller and manipulate/save the copy.

app.controller('Ctrl1', function ($scope, InitApp) {
    $scope.user = angular.copy(InitApp);
});

This disconnects the controller object from the service object, leaving you with one source of truth in the service. Cancel can just rebind to the service object.

Also, in your fiddle you are returning properties and manipulating the service in your controller. You need to return an object instead so you are not manipulating the service directly and breaking it.

http://jsfiddle.net/bfelda/8btk5/45/

Upvotes: 2

Angel Villalain
Angel Villalain

Reputation: 595

If you are interested in having like a roll back to the original values in case the user clicks on a Cancel button, you should have a copy of the model retrieved from the service, and bind to the copy.

If the user clicks Cancel you should discard this copy and reinitialize all values with the original object. Saving the object will require to update the model accordingly and so on.

Upvotes: 1

sfletche
sfletche

Reputation: 49744

I'm not exactly sure I follow your question, but maybe this helps...

The model binding in Angular is only saving the value to your controller and not to your factory.

If you are hoping to update the values in your factory, you'll want to do that within the save method (by calling methods internal to the factory service).

Upvotes: 0

Related Questions