Search code examples
angularjsservicefactorycontrollers

Share Data in AngularJs


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}}

Solution

  • 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}}