$ routeProvider - 根据URL注入控制器的依赖 [英] $routeProvider - injecting controller dependencies depending on URL
问题描述
考虑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) {...});
根据URL,我想无论是全球信任度调查报告
或 StrategyTwo
或 StrategyThree
被注入,施工时 myController的
。一个伪code来说明的理念是:
Depending on URL, I want either StrategyOne
, or StrategyTwo
, or StrategyThree
to be injected, when constructing MyController
. A pseudo-code to illustrate the idea:
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" });
});
任何变化,我可以做到这样的事情与AngularJS?
Any change I can achieve something like this with AngularJS?
推荐答案
是的! AngularJS可以轻松地处理这个pretty日Thnx到决心
路由定义(详细信息的here )。
Yes! AngularJS can handle this pretty easily thnx to the resolve
property of a route definition (more info here).
所以,基本上你可以写这样的:
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"}});
});
有注入到您的控制器正确的策略! AngularJS DI在其最好的!
to have the proper strategy injected into your controller! AngularJS DI at its best!
有一个非常不错的视频教程对付决心
主题,你会觉得很有趣:<一href=\"http://www.youtube.com/watch?v=P6KITGRQujQ&list=UUKW92i7iQFuNILqQOUOCrFw&index=4&feature=plcp\">http://www.youtube.com/watch?v=P6KITGRQujQ&list=UUKW92i7iQFuNILqQOUOCrFw&index=4&feature=plcp
There is a very good video tutorial dealing with the resolve
topics, you might find it interesting: http://www.youtube.com/watch?v=P6KITGRQujQ&list=UUKW92i7iQFuNILqQOUOCrFw&index=4&feature=plcp
这篇关于$ routeProvider - 根据URL注入控制器的依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!