Angular 在 stateprovider 的 templateurl 中传递参数

Angular pass parameters in templateurl in stateprovider

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

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

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

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

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

但显然我的语法在这里是错误的。 我如何实现这种情况?

created working example。正在调整Q&A:

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

  $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) {}
    });

现在我们可以这样称呼它

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

检查一下here

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

$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) {}
});