javascript $routeProvider - 根据 URL 注入控制器依赖项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13037051/
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-26 17:41:41  来源:igfitidea点击:

$routeProvider - injecting controller dependencies depending on URL

javascriptdependency-injectionangularjs

提问by Andrey Agibalov

Consider the code:

考虑代码:

var app = angular.module("app", [], function($routeProvider) {
  $routeProvider
    .when("/page1", { controller: "MyController" })
    .when("/page2", { controller: "MyController" })
    .when("/page3", { controller: "MyController" });
});

app.factory("StrategyOne", function() {...});
app.factory("StrategyTwo", function() {...});
app.factory("StrategyThree", function() {...});

app.controller("MyController", function(Strategy, $scope) {...});

Depending on URL, I want either StrategyOne, or StrategyTwo, or StrategyThreeto be injected, when constructing MyController. A pseudo-code to illustrate the idea:

根据URL,我想无论是StrategyOneStrategyTwo,或StrategyThree将被注入,施工时MyController。一个伪代码来说明这个想法:

var app = angular.module("app", [], function($routeProvider) {
  $routeProvider
    .when("/page1", { controller: "MyController", Strategy: "StrategyOne" })
    .when("/page2", { controller: "MyController", Strategy: "StrategyTwo" })
    .when("/page3", { controller: "MyController", Strategy: "StrategyThree" });
});

Any change I can achieve something like this with AngularJS?

我可以用 AngularJS 实现这样的改变吗?

回答by pkozlowski.opensource

Yes! AngularJS can handle this pretty easily thnx to the resolveproperty of a route definition (more info here).

是的!AngularJS 可以很容易地处理这个问题resolve,因为路由定义的属性(更多信息在这里)。

So, basically you could write something like:

所以,基本上你可以写这样的东西:

var app = angular.module("app", [], function($routeProvider) {
  $routeProvider
    .when("/page1", { controller: "MyController", resolve: {Strategy: "StrategyOne"}})
    .when("/page2", { controller: "MyController", resolve: {Strategy: "StrategyTwo"}})
    .when("/page3", { controller: "MyController", resolve: {Strategy: "StrategyThree"}});
});

to have the proper strategy injected into your controller! AngularJS DI at its best!

将正确的策略注入您的控制器!AngularJS DI 处于最佳状态!

There is a very good video tutorial dealing with the resolvetopics, you might find it interesting: http://www.youtube.com/watch?v=P6KITGRQujQ&list=UUKW92i7iQFuNILqQOUOCrFw&index=4&feature=plcp

有一个非常好的处理这些resolve主题的视频教程,您可能会觉得它很有趣:http: //www.youtube.com/watch?v=P6KITGRQujQ&list=UUKW92i7iQFuNILqQOUOCrFw&index=4&feature=plcp