AngularJS - 有没有办法在不使用路由的情况下将数据注入控制器? [英] AngularJS - Is there a way to inject data into a controller without using routes?

查看:37
本文介绍了AngularJS - 有没有办法在不使用路由的情况下将数据注入控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Angular 应用程序中有一个控制器,需要一些服务器端初始化.我想同步进行,这意味着应该在启动控制器之前获取数据.我在应用程序配置中使用 routeProvider 同步加载和注入数据到许多其他控制器:

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"); }] }
        })

但是我有一个控制器,它没有与之关联的特定路由或 templateUrl.它位于许多不同页面和路由使用的共享布局页面中.我试过这个,假设路线/"下的所有东西都必须通过那个,但它没有用:

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.

推荐答案

如果你只是想避免重复设置resolve,你可以像下面这样写.

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.

这篇关于AngularJS - 有没有办法在不使用路由的情况下将数据注入控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆