Route resolving + multiple controller combo?

我们两清 提交于 2019-12-12 03:16:40

问题


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...

  1. In the base controller, add the local variable as a $scope variable (seems dirty, especially for large controllers)
  2. Move it into a service (it's not really relevant to any services though...)
  3. ??

回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!