AngularJS - loading data before loading any controller

I am making a Single Page Application (SPA). I made a controller called InitialControler

to download data from server to this url (local.app/init).

I want this url to be opened before any other url. I am using ui-router i did $state.go('init')

in function .run()

but it still loads requested page before page'init'

+3


source to share


3 answers


One way to do this is to declare only the "init" state in config. And in the InitialController, after loading the data (service call resolution function), configure other states. But in this approach, when you refresh the page, the url will change to local.app.init.



To stay in this particular state even after a reboot, the solution I found was to have a StartUp application into which I loaded the required data, and after that I loaded the main application manually using angular.bootstrap.

+3


source


First create a state named app

$stateProvider.state('app', {
    abstract:    true,
    templateUrl: "assets/partials/container.html",
    controller:  'AppCtrl',
    resolve: {
        init: function(MyFactory) {
            return MyFactory.resolver();
        }
    }
});

      

Now, any new state you create should be a child of the state app

. This is also a good thing because it becomes your root area. And the state will not be processed unless your factory is resolved.

This is how you create your factory

app.factory('MyFactory', function($http){
    var items = [];
    return {
        resolver: function(){
            return $http.get('my/api').success(function(data){
                items = data;
            })
        },
        get() {
            return items;
        }
    }
});

      



Now in any other state

$stateProvider.state('app.items', {
    url:    '/items',
    templateUrl: "assets/partials/items.html",
    controller:  function($scope, MyFactory){
        $scope.items = MyFactory.get();
    }
});

      

More about the sate solution

https://github.com/angular-ui/ui-router/wiki#resolve

+11


source


If you are using ui-router then you can resolve this with nested states. For example:

$stateProvider
    .state("main", {
        url: "/",
        template: '<div ui-view></div>',
        controller: 'InitController'
    })
    .state("main.landing", {
        url: "landing",
        templateUrl: "modules/home/views/landing.html",
        controller: 'LandingPageController'
    })
    .state("main.profile", {
        url: "profile",
        templateUrl: "modules/home/views/profile.html",
        controller: 'ProfileController'
    });

      

In this example, you have defined 3 routes: "/", "/ landing", "/ profile"

This way, the InitController (associated with the "/" route) is always called, even if the user enters directly into / landing or / profile

Important: Don't forget to enable <div ui-view></div>

to enable loading controller child states in this section

+4


source







All Articles