简体   繁体   中英

AngularJS - Is there a way to inject data into a controller without using routes?

I have a controller in my angular application that requires some server-side initialization. I would like to do it synchronously, meaning that the data should be fetched before the controller is initiated. I synchronously load and inject data into many other controllers using the routeProvider in application configuration:

$routeProvider
        .when('/Home', {
            templateUrl: 'default/home', controller: 'homeController',
            resolve: { 'InitPageData': ['initPageService', function (initPageService) { return initPageService.init("home/initpage"); }] }
        })

but I have this one controller that doesn't have a certain route or templateUrl that it's associated with. It's in a shared layout page used by many different pages and routes. I tried this, assuming that everything under the route '/' will have to pass through that, but it didn't work:

.when('/', {    // doesn't work
            controller: 'appController',
            resolve: { 'AppData': ['initPageService', function (initPageService) { return initPageService.init("something/initpage"); }] }
        })

I don't know all the routes that will end up using this controller and I don't want to care about it. Is there a way that I could specifically resolve data and inject into a controller regardless of where it's invoked? Thanks in advance.

You could have appController be parent controller for all your other controllers.

Something similar to this:

<html ng-controller="appController">

Inside appController you could have a self executing anonymous function call which does the pre-load stuff for all your other controllers.

If you want to restrict certain child controller behavior then use a scope variable in appController to regulate them.

This is classic case of using custom events to tell other parts of application of "resolve". JS is asynchronous - you should either watch for properties, or watch of events on rootScope or use promises to handle dependent tasks.

If what you want to achieve is only avoiding to set resolve repeatedly, you could write something like below.

.config(function($routeProvider) {
    function when(path, config){
        if (/* you can test path with regex or something */){
            config.resolve = { 'AppData': ['initPageService', function (initPageService) { return initPageService.init("something/initpage"); }] };
        }
        return $routeProvider.when(path, config);
    }
    when('/Home', {
        templateUrl: 'default/home', controller: 'homeController'
    })
    .when(...)
    ;
})

I hope it would bring some idea to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM