是否可以通过Angular中的UI-Router的AJAX请求加载模板?

die*_*lar 2 state angularjs angular-template angular-ui-router

我知道这可能会得到一个答案,但是对于延迟加载实现本身来说更多.

所以,这是一个典型的UI-Router配置块:

app.config(function($stateProvider, $urlRouterProvider, $injector) {
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'view_home.html',  // Actually SHOULD BE result of a XHR request ....
            controller: 'HomeCtrl'
        });
});
Run Code Online (Sandbox Code Playgroud)

但是,如果我想在templateUrl请求($stageChangeStart)时加载它,那将是基于AJAX请求的.

应该如何实施?LARGE角应用程序如何处理这个问题?

Rad*_*ler 5

我们应该(在这种情况下)使用TemplateProvider.来自doc的小小的引用:

模板

TemplateUrl
... templateUrl也可以是返回url的函数.它需要一个预设参数stateParams,它不是注入的.

TemplateProvider
或者您可以使用模板提供程序函数,该函数可以注入,可以访问本地,并且必须返回模板HTML,如下所示:

$stateProvider.state('contacts', {
  templateProvider: function ($timeout, $stateParams) {
    return $timeout(function () {
      return '<h1>' + $stateParams.contactId + '</h1>'
    }, 100);
  }
})
Run Code Online (Sandbox Code Playgroud)

还有更多.

我们可以使用真正强大的合作

$templateRequest

在这个Q&A (基于来自API Ajax Call的slug的Angular UI-Router动态路由.基于slug的加载视图)中,我们可以看到如此简单的templateProvider定义

.state('hybrid', {
    // /john-smith
    url: '/:slug',
    templateProvider: ['type', '$templateRequest',
      function(type, templateRequest) 
      {
        var tplName = "tpl.partial-" + type + ".html";
        return templateRequest(tplName);
      }
    ],
Run Code Online (Sandbox Code Playgroud)

结果也是......

还有其他类似问答的链接,包括工作示例