使用 AngularJS 路由时有没有办法预加载模板? [英] Is there a way to preload templates when using AngularJS routing?

查看:26
本文介绍了使用 AngularJS 路由时有没有办法预加载模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

加载 Angular 应用后,我需要一些模板才能离线使用.

After the Angular app is loaded I need some of the templates to be available offline.

这样的事情是理想的:

$routeProvider
  .when('/p1', {
    controller: controller1,
    templateUrl: 'Template1.html',
    preload: true
  })

推荐答案

有一个模板缓存服务:$templateCache 可用于在 javascript 模块中预加载模板.

There is a template cache service: $templateCache which can be used to preload templates in a javascript module.

例如,取自文档:

var myApp = angular.module('myApp', []);
  myApp.run(function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});

甚至还有一个从 html 文件预生成 javascript 模块的繁重任务:grunt-angular-templates

There is even a grunt task to pre-generate a javascript module from html files: grunt-angular-templates

另一种可能不太灵活的方法是使用内联模板,例如,在 index.html 中使用这样的脚本标记:

Another way, perhaps less flexible, is using inline templates, for example, having a script tag like this in your index.html:

<script type="text/ng-template" id="templates/Template1.html">template content</script>

表示模板可以在以后以与路由配置中的真实 url 相同的方式寻址 (templateUrl: 'templates/Template1.html')

means that the template can be addressed later in the same way as a real url in your route configuration (templateUrl: 'templates/Template1.html')

这篇关于使用 AngularJS 路由时有没有办法预加载模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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