stateprovider中templateurl中的角度传递参数 [英] Angular pass parameters in templateurl in stateprovider

查看:36
本文介绍了stateprovider中templateurl中的角度传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 angular 应用程序中使用 angular-ui-router 中的 $stateprovider 如下:

I am using a $stateprovider as follows from angular-ui-router in my angular application:

.state('order', {
        url: "/order/:id",
        templateUrl: "/myapp/order"
    })

在上面的场景中,我们将一个 id 传递给控制器​​,我们可以将其称为 ui-sref="order({id: 1234})".

In the above scenario, we are passing an id to the controller and we can call it as ui-sref="order({id: 1234})".

但现在我想通过不使用控制器直接调用后端并按如下方式传递:

But now i want to make a direct call to the backend by not using a controller and pass the above as follows:

.state('order', {
        url: "/order",
        templateUrl: "/myapp/order/:id"
    })

但显然我的语法在这里是错误的.我如何实现这个场景?

But obviously my syntax is wrong here. How do i achieve this scenario?

推荐答案

创建了工作示例.它正在调整 thiw Q &答:

I created working example. It is adjsuting thiw Q & A:

让我们在示例中使用模板 template-A.htmltemplate-B.html.templateProvider 的状态定义看起来像这样

Let's have templates template-A.html and template-B.html in our example. The state def with templateProvider would look like this

  $stateProvider
    .state('order', {
      url: '/order/:id',

      templateProvider: function($http, $templateCache, $stateParams) {

        var id = $stateParams.id || 'A';
        var templateName = 'template-' + id + '.html';

        var tpl = $templateCache.get(templateName);

        if (tpl) {
          return tpl;
        }

        return $http
          .get(templateName)
          .then(function(response) {
            tpl = response.data
            $templateCache.put(templateName, tpl);
            return tpl;
          });
      },
      controller: function($state) {}
    });

现在我们可以这样称呼它

And now we can call it like this

  <a href="#/order/A">
  <a href="#/order/B">

检查它这里

更重要的是,使用最新版本的 angularjs,我们甚至可以让它变得超级简单:

And what's more, with latest version of angularjs we can even make it super simple:

$templateRequest

更新了plunker

.state('order', {
  url: '/order/:id',

  templateProvider: function($templateRequest, $stateParams) {

    var id = $stateParams.id || 'A';
    var templateName = 'template-' + id + '.html';
    return $templateRequest(templateName);
  },
  controller: function($state) {}
});

这篇关于stateprovider中templateurl中的角度传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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