1

How to Share data to all controller?

I have a controller that pull data from server(file.json) that i want to share to other controller

sampleApp.controller('PhoneListCtrl', 
['$scope', '$http', 
function($scope, $http) {
    $http.get('App_Data/phonelist.json').
        success(function(returnDataFrmJson){
            $scope.phonesScope = returnDataFrmJson;
        });
}]);

controller that will access the shared data of the first one

sampleApp.controller('AddIPhoneController', 
['$scope', '$http',
function($scope, $http) { 
    $scope.newInput= 'sample text';

    $scope.sharedText= dataFromSharedControll;
}]);

the html file that will show the data.

{{newInput}} {{sharedText}}

6 Answers6

2

Well, there are various options for you like using: $sessionStorage, localStorage, appConstant, $localStorage and so on.

You can even share the data between controllers using Factory and Services. I will be giving you a simple example of using $sessionStorage.

In order to use $sessionStorage or $localStorage, you need to inject ngStorage.

First in your index.html, include the source:

<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>    

Then in your module definition, inject the ngStorage:

var sampleApp = angular.module('Your App Name', ['ngStorage']);  

And , in your controllers:

sampleApp.controller('PhoneListCtrl', 
['$scope', '$http', '$sessionStorage',
function($scope, $http,$sessionStorage) {
    $http.get('App_Data/phonelist.json').
        success(function(returnDataFrmJson){
            $scope.phonesScope = returnDataFrmJson;
            $sessionStorage.sharedValue = returnDataFrmJson;//keeping the value in session
        });
}]);    

controller that will access the shared data of the first one

sampleApp.controller('AddIPhoneController', 
['$scope', '$http','$sessionStorage',
function($scope, $http,$sessionStorage) { 
    $scope.newInput= 'sample text';

    $scope.sharedText= $sessionStorage.sharedValue;
}]);

Then in your View:

{{newInput}}{{sharedText}}
Sunil Lama
  • 4,531
  • 1
  • 18
  • 46
  • this one works like magic ^^, thanks, but how can i get exact data since its in json format. like [{"name":"oneName", "address":123},{"name":"twoName", "address":341}] – Raymond Manalili Mar 17 '16 at 09:51
  • You can access those in the view as {{sharedText.name}} {{sharedText.address}} as such. – Sunil Lama Mar 17 '16 at 09:59
  • got it. by "." binding in view ^^, do you have comparison of this services and localstorage who/which is good for that – Raymond Manalili Mar 17 '16 at 10:00
  • well, using service and factory is always the best option.The datas are persistent when it comes to localstorage and sessionstorage, you commensurate problems with memory dumps and all, and the need to destroy it at the end sometimes comes as a confusion as to where. I think there are lots of articles comparing the differences. you can GOOGLE it :) ^^ – Sunil Lama Mar 17 '16 at 10:03
0

If I understand your question correctly you could create a service and inject it to other controllers like so:

    sampleApp.service('sharedProperties', function() {
        var sharedText = '';
        return {
            getSharedText: function() {
                return sharedText;
            },
            setSharedText: function(newText) {
                sharedText = newText;
            }
        }
    }

And then in your controller:

    sampleApp.controller('ControllerName', ['sharedProperties', function(sharedPropertied) {
        var text = sharedProperties.getSharedText();
    }]);

Obviously you should set the text somewhere by injecting the service and setting it in another controller.

LosGlennos
  • 99
  • 10
0

You should share data via a service. Also the $http calls in the controller should be moved to a service. If you then inject the service in the controller, you can call the methods/data from that service in the controller.

I suggest you take a look at John Papa's style guide found here: https://github.com/angular/angular

0

You are doing wrong the data you want to share between controllers should exist in service not controller

Service :

 sampleApp.service("MyService",function($http){
       this.phoneList = function(){
             return $http.get('App_Data/phonelist.json');
       };         
 });

Controller 1 :

  sampleApp.controller('PhoneListCtrl1',function($scope,MyService) {
        MyService.phoneList()
           .then(function(list){
                 $scope.phoneList = list;
            });
    });

Controller 2 :

 sampleApp.controller('PhoneListCtrl2',function($scope,MyService) {
            MyService.phoneList()
               .then(function(list){
                     $scope.phoneList = list;
                });
    });
Amit Sirohiya
  • 333
  • 1
  • 13
0

Try $rootScope.phonesScope. This may help. understand rootscope

Jomon Antony
  • 258
  • 3
  • 15
0

It depends on the requirements:

  1. If your purpose is to share the data among controllers without notifying the controllers when the data is populated/updated, go with the service/factory approach.
  2. If you also want to notify the other controllers while populating/updating the data then you can make use of angular events($broadcast/$emit).
  3. And if you want to preserve the data on page refresh or browser close, you can opt for session/local storage.
Harpreet
  • 1,527
  • 13
  • 25