问题
I'm trying to combine 2 concepts and I'm having trouble making them work together.
Concept 1
: Route resolving. This is easy to explain, I just want to resolve certain models like this:
$routeProvider
.when("/news", {
templateUrl: "news.html",
controller: "newsCtrl",
resolve: { news: function(Model) { return Model.news.getList(); }
Concept 1
: The idea of a 'base controller' that I can use in the route controller: xyz
, then in the actual view html I load the 'sub' controller. For instance....
app.js
$routeProvider
.when("/news/latest", {
templateUrl: "news-latest.html",
controller: "newsCtrl"
news-latest.html
<div ng-controller="newsLatestCtrl">
...
</div>
This will allow me to put my common code inside newsCtrl
, and /news/latest
specific code in newsLatestCtrl
The problem is I need to combine these two concepts, but it's hard to do that because I can't pass the local variables in to the 'sub' controller, only the main controller.
The only options I see don't really look like good ideas...
- In the base controller, add the local variable as a
$scope
variable (seems dirty, especially for large controllers) - Move it into a service (it's not really relevant to any services though...)
- ??
回答1:
It's hard to help you when we don't know what the "base controller"'s responsibilities are. For me, the Concept 3 you are looking for is as follows:
$routeProvider
.when("/news", {
templateUrl: "news.html",
controller: "newsCtrl",
resolve: { news: function(Model) { return Model.news.getList(); })
.when("/news/latest", {
templateUrl: "news.html",
controller: "newsLatestCtrl"},
resolve: { newsLatest: function(Model) { return Model.news.getLatest(); });
module.controller('newsCtrl', function($scope, news) {
/* common code you want to share */
});
module.controller('newsLatestCtrl', function($scope, newsLatest, $controller) {
// instantiate your "base controller"
var ctrl = $controller('newsCtrl', {
"$scope": $scope,
"news": newsLatest
});
// customize and add special code for latest news
});
来源:https://stackoverflow.com/questions/27849332/route-resolving-multiple-controller-combo