Search code examples
angularjsangularjs-scopecontrollersdata-sharing

AngularJS: How do I share data accross all pages and controller of my SPA?


What is the best way to share some data across all controllers and scopes of my Single page application ?

Let say i have a small set of data I want to be able to access everywhere, and I don't want to query the database every time I need it.


Solution

  • Shared data services seems to be the best aproach for your case. There is $rootScope as a global scope, but, $rootScope shoudn't be used for such thing due to performance issues. $rootscope is part of angular digest cycle, so when you add something to it, you are also adding something more to be checked. Therefore, it's not recommended to use unless it's extremely necessary.

    For example, for simple services:

    app.service('SharedDataService', function () {
         var Data = {
            field1: 'qweqwe',
            field2: '12312'
        };
    
        return Data;
    });
    

    For complex services with async operations:

    app.service('SharedDataService', function () {
        var self = this; 
        this.getData = function () {
            if(self.cachedData){
                return $q.resolve(self.cachedData);
            }
    
            return $http.get('my-data-url').then(function (response) {
                self.cachedData = response.data;
                return self.cachedData;
            });
        };
    });
    

    And the controller:

    app.controller('MyController', function ($scope, SharedDataService) {
        SharedDataService.getData().then(function (data) {
            $scope.data = data;
        });
    });