AngularJS,使用不同模板但使用同一控制器的多条路线怎么样? [英] AngularJS, How about multiple routes with different templates but the same controller?

查看:78
本文介绍了AngularJS,使用不同模板但使用同一控制器的多条路线怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调查我能否获得标题中的内容。
这是我的想法。

i'm investigating if i can have what the title says. Here's my thought.

让我们假设我有以下路线:

Let's assume that i've got this routes:

  .when('/', {
        templateUrl : 'partials/homepage.html',
  })

  .when('/test', {
        templateUrl : 'partials/test.html',
  })

  .when('/page/:pageID', {
        templateUrl : 'partials/page.html',
  })

  .when('/page/single/:pageID', {
        templateUrl : 'partials/page-single.html',
  })

直到现在我有机会添加templateUrl以及控制器详细信息

Until now i had the opportunity to add the templateUrl as also the controller details in the route and everything was working just fine.

现在,应用程序已更改,只有一个控制器具有所有需要的信息,并且必须保留一个控制器。路线将是这样的:

Now the app is changed and there is only one controller with all the information needed and must remain one controller. And the routes will be something like that:

  .when('/:templateName/:pageID', {
       controller: 'myCtrl'
  })

我可以从控制器设置模板ID吗获取templateName参数?如果是的话,最后一个路由示例/ page / single /:pageID呢?我怎么知道路由中还有第二个选项?

Can i set from the controller the template id by getting the templateName parameter? And if so how about the last route example /page/single/:pageID? How can i know that there is a second option in route?

我可以使用templateName参数,并使用$ routeChangeSuccess方法查看它的变化,但我找不到任何方法

I can take the templateName parameter and see it changing with the $routeChangeSuccess method but i cannot find any way to set the template on the fly.

有什么想法吗?

推荐答案

一种解决方案可以是以下解决方案:

One solution could be the following one:

angular.module('myapp', []).
            config(['$routeProvider', function($routeProvider) {
            $routeProvider.when('/:templateName/:pageId', {
                templateUrl: function(urlattr){
                    return '/pages/' + urlattr.templateName + '.html';
                },
                controller: 'YourCtrl'
            });
        }
    ]);

来自AngularJs 1.3文档:


templateUrl – { string | function()} –返回ngView应该使用的html模板的路径或路径。

templateUrl – {string|function()} – path or function that returns a path to an html template that should be used by ngView.

如果templateUrl是一个函数,将使用以下参数调用它:
Array。< Object> -从当前 $位置提取的路由参数。通过应用当前路线来获得path()

If templateUrl is a function, it will be called with the following parameters: Array.<Object> - route parameters extracted from the current $location.path() by applying the current route

这篇关于AngularJS,使用不同模板但使用同一控制器的多条路线怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆