11

考虑代码:

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,我StrategyOne希望StrategyTwoStrategyThree构造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实现这样的改变吗?

4

1 回答 1

25

是的!AngularJS 可以resolve通过路由定义的属性轻松处理这个问题(更多信息在这里)。

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

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

于 2012-10-23T18:59:11.630 回答