javascript 在 angularjs $routeProvider 中动态加载控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18423054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:51:44  来源:igfitidea点击:

dynamically loading the controller in angularjs $routeProvider

javascriptangularjsangularjs-routing

提问by Kia Panahi Rad

I currently have an AngularJS app with routing built in and it works perfectly with static controllerproperty assignments. but what I really want to do is to dynamically assign controllers with different routes:

我目前有一个内置路由的 AngularJS 应用程序,它与静态controller属性分配完美配合。但我真正想做的是动态分配具有不同路由的控制器:

$routeProvider
 .when("/Dashboards/:dashboardName",{
    templateUrl:function(params) {
                 return "Dashboards/" + params.dashboardName;
                //some ASP.NET MVC calls to return partial views (this part works)
        }
  })

What I would like to do is to do the same thing about my controllerproperty here, like:

我想做的是对我controller在这里的财产做同样的事情,例如:

$routeProvider
 .when("/Dashboards/:dashboardName",{
       templateUrl:function(params) {
             return "Dashboards/" + params.dashboardName;
            //some ASP.NET MVC calls to return partial views (this part works)
           },
       controller: function(params) {
             return params.dashboardName+"Controller"; (this part DOESN'T work)
           }
  })

but as it seems I am get an error saying paramsProvideris not found

但似乎我收到一条错误消息,说paramsProvider没有找到

so is there any way I could dynamically load my controller function name in route configuration?

那么有什么方法可以在路由配置中动态加载我的控制器函数名称?

采纳答案by Bradley Trager

This is possible to do using angular ui-router.

这可以使用angular ui-router 来完成

The ui-router lets you specify a "controllerProvider" to specify a function for providing a controller. So the solution would look like this:

ui-router 允许您指定“controllerProvider”来指定提供控制器的功能。所以解决方案看起来像这样:

$stateProvider
.state("/Dashboards/:dashboardName",{
   templateUrl:function($stateParams) {
         return "Dashboards/" + $stateParams.dashboardName;
       },
   controllerProvider: function($stateParams) {
         return $stateParams.dashboardName+"Controller";
       }
  })

I hope it helps!

我希望它有帮助!

回答by Nathaniel Johnson

I solved this issue by not specifying the controller in $routeProvider but instead placing it in the file specified in templateURL.

我通过不在 $routeProvider 中指定控制器而是将它放在 templateURL 中指定的文件中来解决这个问题。

$routeProvider
 .when("/Dashboards/:dashboardName",{
    templateUrl:function(params) {
                 return "Dashboards/" + params.dashboardName;
        }
  })

In DashboardsNAME.html

DashboardsNAME.html

<div class="container" ng-Controller='DashboardsNAMEController'>Food</div>

This technique still requires that at some point before the route is instantiated you have registered DashboardsNAMEController. I suspect that the best place to do it is in the module.run()method with call to your own service but I do it in my main controller because it works and is a short controller anyway.

这种技术仍然需要在路由被实例化之前的某个时间点注册DashboardsNAMEController。我怀疑最好的module.run()方法是在调用您自己的服务的方法中执行此操作,但我在主控制器中执行此操作,因为它可以工作并且无论如何都是一个简短的控制器。

回答by mettjus

I don't know if it depends on AngularJS version but you can serve a function to the controllerproperty, the function becoming the actual controller. Using this fact in conjunction with controller inheritanceyou can obtain a more condensed code like the one you were looking for, I think:

我不知道它是否取决于 AngularJS 版本,但您可以为该controller属性提供一个函数,该函数成为实际控制器。将此事实与控制器继承结合使用,您可以获得更简洁的代码,就像您正在寻找的那样,我认为:

$routeProvider
.when("/Dashboards/:dashboardName",{
    templateUrl:function(params) {
        return "Dashboards/" + params.dashboardName;
    },
    controller: function($scope, $routeParams, $controller) {
        /* this creates a child controller which, 
           if served as it is, should accomplish 
           your goal behaving as the actual controller
           (params.dashboardName + "Controller") */
        $controller($routeParams.dashboardName + "Controller", {$scope:$scope});
    }
})

Disclaimer: I honestly don't know if this approach has any drawbacks. Doesn't look so though.

免责声明:老实说,我不知道这种方法是否有任何缺点。不过看起来不是这样。

回答by Benjamin Oman

I have been attempting this same thing. One solution I've found is to do this inside your routeProvider:

我一直在尝试同样的事情。我发现的一种解决方案是在您的 routeProvider 中执行此操作:

 $routeProvider
    .when("/Dashboards/:dashboardName",{
        templateUrl:function(params) {
            return "Dashboards/" + params.dashboardName;
        },
        controller: 'dynamicController'
 });

And then you do your calculation for what "pseudo-controller" (for lack of a better name) to load inside of the "dynamicController" definition.

然后你计算在“dynamicController”定义中加载什么“伪控制器”(因为没有更好的名字)。

var controllers = {
    unoController: function($scope, $routeParams, $rootScope) {
        // Do whatever
    },
    dosController: function($scope, $routeParams, $rootScope) {
        // Whatever for this controller
    }
}

app.controller('dynamicController', ['$scope', '$routeParams', '$rootScope', function($scope, $routeParams, $rootScope) {
    controllers[$routeParams.dashboardName+"Controller"]($scope, $routeParams, $rootScope);
}]);

This assumes that $routeParams.dashboardName is one of ["uno","dos"].

这假设 $routeParams.dashboardName 是 ["uno","dos"] 之一。

Take this with a grain of salt as I've only had about 3 days with Angular, but so far this approach has worked great for what I'm trying to accomplish.

对此持保留态度,因为我只使用了 3 天的 Angular,但到目前为止,这种方法对我想要完成的工作非常有效。

回答by CENT1PEDE

Here is something that also works, (at least for me). This may help future people searching for answer.

这也适用(至少对我而言)。这可能有助于未来的人们寻找答案。

$stateProvider
    .state('foo', {
        url: '/foo/:bar',
        templateUrl: 'some-template-path.html',
        resolve : {
            getController : function($stateParams){
                if ($stateParams.bar === "tab1") {

                    return "tab1Controller"

                }else if ($stateParams.bar === "tab2") {

                    return "tab2Controller"

                }else if ($stateParams.bar === "tab3"){

                    return "tab3Controller"

                }else if ($stateParams.bar === "tab4") {

                    return "tab4Controller"

                }
            }
        },
        controllerProvider: function(getController){
            return getController;
        },

Not the shortest code but at least easier to read. Also if you want to give the controllera different name from the tab/dashboardName name.

不是最短的代码,但至少更容易阅读。此外,如果您想为controllertab/dashboardName 名称提供不同的名称。