ui-router 动态模板路径 [英] ui-router dynamic template path

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

问题描述

我使用的是 ui-router 0.2.8.我想根据设备宽度加载模板.我可以毫无问题地获得设备宽度,将其设置在范围等中,但我可以弄清楚如何将其绑定到 $stateParams.我在另一个控制器中有范围变量,它可以访问状态的控制器,但状态本身不可用.我试过 templateProvider 但这只是返回一个字符串.我还可以尝试什么才能使其发挥作用?

I'm using ui-router 0.2.8. I'm wanting to load a template based on device width. I can get the device width without issue, set it in the scope etc but I can figure out how to bind it to $stateParams. I have the scope variable in another controller which can be accessed the state's controller it's just not available to the state itself. I've tried the templateProvider but that is only returning me a string. What else can I try in order for this to work?

.state('list', {
abstract: true,
url: "/list",
templateUrl: 'views/'+$stateParams.somevalue+'/page.html',
    controller: "myCtrl"
 })
  .state('list.first', {
url: "/first",
templateUrl: "views/first.html"
  })

推荐答案

您可以在 $stateChangeStart 事件中访问状态参数.您也可以在那里动态更新 templateUrl.

You can access to state params in the $stateChangeStart event. You can also dynamically update the templateUrl there as well.

所以也许你的代码看起来像这样:

So perhaps your code might look something like this:

angular.module('app', ['ui.router'])
.run(function($rootScope){
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
        if (toState.name === 'list') {
          toState.templateUrl = 'views/'+toParams.somevalue+'/page.html';
        }
    });
}

您可能还想看看 ui.router 支持 onEnter 回调.我以前没有使用过它,但它可能比将模板生成代码放入 $stateChangeStart 事件中更简洁.

You might also want to take a look at the onEnter callback supported by ui.router. I have not used this before but it might be neater than putting your template generating code into the $stateChangeStart event.

这篇关于ui-router 动态模板路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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