Skip to main content
 首页 » 编程设计

angularjs之如何在 Angular UI 路由器中预加载模板

2024年07月26日123dflying

我正在使用 Angular UI 路由器。我有很多这样的模板调用:

var access = { 
        name: 'access', 
        templateUrl: 'app/access/partials/a1.html', 
    }; 

Access 提供的页面取决于 :content。

有没有一种方法可以将所有这些 HTML 文件合并为一个并预加载这些文件,以便每个操作都不会涉及另一个请求?我意识到我可以将 HTML 直接放入模板中,但是我可以将多个模板中的 HTML 合并到一个文件中并预先加载所有内容,以便在需要时准备就绪吗?

请您参考如下方法:

Is there a way that I could combine all these HTML files into one and pre-load the files so every action didn't involve another request?

,使用html2js

或者,准确地说,一个 grunt/gulp 插件分别称为 grunt-html2js/gulp-html2js

<小时 />

如何运作

根据这个grunt-html2js tutorial :

"html2js 是一个插件 (...),它解析应用程序中的所有模板文件并创建一个填充 $templateCache 的 javascript 文件。

这是一个非常有用的技巧,可以减少应用程序启动应用程序所需的请求数量。

它还可以缩小 html 片段,从而节省一些带宽。”

----------

根据grunt-html2s Github repository :

html2js 将一组模板转换为 JavaScript,并将它们组装成 Angular 模块,该模块在加载模块时直接启动缓存。

您可以将此模块与主应用程序代码连接起来,以便 Angular 不需要发出任何额外的服务器请求来初始化应用程序。”

----------

据我所知:)

我喜欢 html2js 的一点是,您不需要更改任何 Angular 代码,而只需配置 gruntfile.js/gulpfile.js.

您的 templateUrl 文件将 automagically可在 $templateCache 中使用。

所以它完全符合您的要求:

  • 将所有模板合并到一个模块中;
  • 编写模块的 JavaScript 源代码;

您需要做的就是将该模块指定为代码中的依赖项。

Once the module is loaded, all your templates are available in the cache: no request needed!

<小时 />

GRUNT/GULP 配置示例

grunt.initConfig({ 
  html2js: { 
    options: { 
    base: 'app', 
    module: 'templates', 
    htmlmin: { 
      ... many available options: see GitHub repo ... 
    } 
  }, 
    main: { 
      src: ['app/**/*.html'], 
      dest: 'templates.js' 
    }, 
  }, 
}) 

然后只需使用模板模块作为依赖项:

angular.module('myApp', [ 'templates']); 

----------

以下是来自 gulp-html2js GitHub 存储库的示例:

gulp.task('scripts', function() { 
  gulp.src('fixtures/*.html') 
    .pipe(html2js({ 
      outputModuleName: 'template-test', 
      useStrict: true 
    })) 
    .pipe(concat('template.js')) 
    .pipe(gulp.dest('./')) 
}) 
<小时 />

测试

此外,html2js也是一个非常好的工具test directives that use the templateUrl property .

<小时 />

了解更多信息

阅读 Joel Hooks 后我遇到了 html2js '(Egghead讲师)book about automation ,我强烈推荐。

Watch a dedicated video about html2js in the pro section EggHead 网站。

Testing directives using the templateUrl property with Karma and karma-ng-html2js-preprocessor

<小时 />

注意

从技术上讲,您可以使用 ng-html2js ,不使用 Gulp 或 Grub;然后您可以使用如下命令行:

ng-html2js inputFile [outputFile] [-m moduleName] [--module-var ngModule] 

但是,由于您需要为每个 templateUrl 文件运行上述命令,Gulp/Grub 自动化似乎是一种更有效的方法。

<小时 />

免责声明

我对我提到的书籍/网站/工具没有特别的兴趣或分享。

注意:我还应该添加,您还可以将此文件添加到您的 html 页面中:

 <script src="path/to/templates.js"></script>