AngularJS 有动态路由吗? [英] Does AngularJS have dynamic routing?

查看:25
本文介绍了AngularJS 有动态路由吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

angular 是否支持动态路由?也许是这样的伎俩:

Does angular support dynamic routing at all? Maybe some trick like this:

$routeProvider.when('/:ctrl/:action', 
                     getRoute($routeParams.ctrl,$routeParams.action))

function getRoute(ctrl, action){
   return {
      templateUrl: ctrl+"-"+action+".html"
      controller: 'myCtrl'
   }
}

请帮帮我,我需要根据 routeParams 获取 templateUrl

Please help me, I need to get templateUrl based out of routeParams

推荐答案

这是一个迟到的答案,但我自己遇到了这个问题,但事实证明 Dan 的解决方案与 ngView 指令上的 ngAnimate 类发生冲突,并且视图显示但 ng-leave 动画将立即应用并隐藏使用他的动态路由打开的视图.

This is a late answer but I came across this problem myself, but it turns out that the solution by Dan conflicts with ngAnimate classes on the ngView directive, and the view is shown but the ng-leave animation will immediately be applied and hide the view opened with his dynamic routing.

我在这里找到了完美的解决方案,它在 1.1.5 + 中可用

I found the perfect solution here, and it's available in 1.1.5 +

$routeProvider中,templateUrl的值可以是一个函数,并传入路由参数:

In the $routeProvider, the templateUrl value can be a function, and is passed the route parameters:

app.config(function ($routeProvider) {
$routeProvider
    .when('/:page', {
         templateUrl: function(routeParams){
             return '/partials/'+routeParams.page+'.html';
        }
    })
});

虽然控制器不能作为函数给出,所以我的解决方案是像往常一样使用 ng-controller="HomeCtrl" 在模板 html 中给出它.

Though the controller can't be given as a function so my solution is to give it in the template html as per usual with ng-controller="HomeCtrl".

使用此解决方案,我们可以在 Angular 中按惯例进行路由.我希望这可以帮助那些不热衷于将每条路线手动添加到 routeProvider 的其他人.

Using this solution we can route by convention in Angular. I hope this helps others who weren't keen on manually adding every route to the routeProvider.

这篇关于AngularJS 有动态路由吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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