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

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

问题描述

我在我的角度应用的控制器,需要一些服务器端的初始化。我想这样做同步,这意味着控制器启动之前的数据应该是牵强。我同步加载并注入使用应用程序配置的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.

推荐答案

如果你想实现的是只避免设置解析一下反反复复,你可以写类似下面

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天全站免登陆