AngularJS : Pass data from one view to another with in same controller

Rohit Jindal picture Rohit Jindal · Dec 23, 2016 · Viewed 7.8k times · Source

Summary :

I have a form in view(first) of my angular application and on success response from the ajax call on submit it redirects the user to the view(second). There is only one controller for the application(for all view). Here, user can enter the fields in the form from the view(first) which should get displayed on the view(second) & again there is a form in the view(second) where user can enter the fields in the form which should get displayed on the view(third).

As all the views(first,second,third) sharing the same controller function.I created one service to set & get the data from one view to another and use this service across the application to send the data from one view to another view sharing the same controller.

Problem statement :

I am not able to store each form data in a separate variable as i am getting the data from the same service across the whole application.

Diagram :

enter image description here

As services are singletons in angular. So they won't be recreated when you go to another page.So, when i call a dataService.setData() method from the controller it removes the previous stored data in the service and updated with new one which creates a problem for me. I want to store all views data separately instead of override with each other.

Answer

Manu Obre picture Manu Obre · Dec 23, 2016

Use a factory with a 'stored' value like this. Add an Identifier per each View, so it will work like a Hash Table.

.factory('storeValue', function() {
    var valueStored= {};
    return {
        getValue: function(viewId) {
            return valueStored[viewId];
        },
        setValue: function(newValue,viewId) {
            valueStored[viewId] = newValue
        }
        deleteOrder: function(viewId) {
            delete valueStored[viewId];
        }
    };
})

Suppose this is the controller for one of your Views, and has as dependency the above factory

$scope.setData = function(){
    storeValue.setValue('value for First View', $state.current.name);
}

$scope.getData = function(){
    storeValue.getValue($state.current.name); // This will return the String 'value for First View'
}

So, You will set a value and an Identifier for the first View. The $state object which represents the current View, will work as an Id of the corresponding View. And you could do the same for the rest of your view, without loosing data.