考虑代码:
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) {...});
根据网址,我希望在构建StrategyOne
时注入StrategyTwo
或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" });
});
我可以用AngularJS实现这样的改变吗?
答案 0 :(得分:25)
是的! AngularJS可以很容易地将这个thnx处理到路由定义的resolve
属性(更多信息here)。
所以,基本上你可以这样写:
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处于最佳状态!
有一个非常好的视频教程处理resolve
主题,您可能会觉得它很有趣:http://www.youtube.com/watch?v=P6KITGRQujQ&list=UUKW92i7iQFuNILqQOUOCrFw&index=4&feature=plcp