是否可以通过 Angular 中的 UI-Router 的 AJAX 请求加载模板? [英] Is it possible to load a template via AJAX request for UI-Router in Angular?

查看:18
本文介绍了是否可以通过 Angular 中的 UI-Router 的 AJAX 请求加载模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能在这里得到答案,但是对于延迟加载实现本身.

I know this might get an answer here, however that goes more for lazy loading implementation itself.

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

So, this is a typical UI-Router config block:

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'
        });
});

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

But what if I want to load such templateUrl when it's requested ($stageChangeStart) and it would be AJAX request based.

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

How should it be implemented? How are LARGE angular applications dealing with this?

推荐答案

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

We should (in this case) use TemplateProvider. Small cite from doc:

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

TemplateUrl
... templateUrl can also be a function that returns a url. It takes one preset parameter, stateParams, which is NOT injected.

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

TemplateProvider
Or you can use a template provider function which can be injected, has access to locals, and must return template HTML, like this:

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

还有更多.

我们可以与真正强大的人合作

We can use cooperation with really powerful

在本问答中A (Angular UI-Router 动态路由基于 API Ajax 调用中的 slug.基于 slug 加载视图) 我们可以看到这么简单的 templateProvider 定义

In this Q & A (Angular UI-Router dynamic routing based on slug from API Ajax Call. Load view based on slug) we can see so simple templateProvider defintion

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

结果也被查了......

and the result is also chached...

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

There are some other links to similar Q & A, including working examples

这篇关于是否可以通过 Angular 中的 UI-Router 的 AJAX 请求加载模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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