16 angularjs angular-ui-router
我正在使用Angular UI路由器.我有很多这样的模板调用:
var access = {
name: 'access',
templateUrl: 'app/access/partials/a1.html',
};
Run Code Online (Sandbox Code Playgroud)
Access提供的页面取决于:content.
有没有办法可以将所有这些HTML文件合并为一个并预先加载文件,以便每个操作都不涉及另一个请求?我意识到我可以将我的HTML直接放在模板中,但是我可以将来自多个模板的HTML合并到一个文件中并将其全部预先加载,以便在需要时准备好吗?
Man*_*ube 19
有没有办法可以将所有这些HTML文件合并为一个并预先加载文件,以便每个操作都不涉及另一个请求?
是的,通过使用html2js
;
或者,确切地说,分别称为grunt-html2js/gulp -html2js的grunt/gulp插件
这个怎么运作
" html2js
是一个插件(...),用于解析应用程序中的所有模板文件,并创建一个填充$ templateCache的javascript文件.
这是减少应用程序启动应用程序所需的请求数量的非常有用的技巧.
它还可以缩小html片段以节省一些bandwitdh."
" html2js
将一组模板转换为JavaScript并将它们组装成一个Angular模块,该模块在加载模块时直接填充缓存.
您可以将此模块与主应用程序代码连接,以便Angular不需要进行任何其他服务器请求来初始化应用程序."
我喜欢的html2js
是你不需要更改任何角度代码,只需配置gruntfile.js
/ gulpfile.js
.
然后,您的templateUrl文件将自动可用$templateCache
.
所以它完全符合你的期望:
您需要做的就是将模块指定为代码中的依赖项.
加载模块后,缓存中将提供所有模板:无需请求!
GRUNT/GULP CONFIG的示例
grunt.initConfig({
html2js: {
options: {
base: 'app',
module: 'templates',
htmlmin: {
... many available options: see GitHub repo ...
}
},
main: {
src: ['app/**/*.html'],
dest: 'templates.js'
},
},
})
Run Code Online (Sandbox Code Playgroud)
然后只使用模板模块作为依赖:
angular.module('myApp', [ 'templates']);
Run Code Online (Sandbox Code Playgroud)
以下是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('./'))
})
Run Code Online (Sandbox Code Playgroud)
测试
更重要的html2js
是,它也是测试使用templateUrl属性的指令的一个非常好的工具.
欲获得更多信息
html2js
在阅读了Joel Hooks(Egghead指导员)关于自动化的书之后我才开始考虑,我强烈推荐这本书.
使用测试指令templateUrl
属性与Karma
和karma-ng-html2js-preprocessor
注意
从技术上讲,你可以使用ng-html2js,而不使用Gulp或Grub; 然后,您可以使用如下命令行:
ng-html2js inputFile [outputFile] [-m moduleName] [--module-var ngModule]
Run Code Online (Sandbox Code Playgroud)
但是,由于您需要为每个templateUrl文件运行上述命令,因此Gulp/Grub自动化似乎是一种更有效的方法.
免责声明
我对我提到的图书/网站/工具没有特别兴趣或分享.
注意:我还应该添加,您还要将此文件添加到您的html页面:
<script src="path/to/templates.js"></script>
Run Code Online (Sandbox Code Playgroud)
为什么不在主html文件中使用ng-include来一次加载所有html.
像这样......
<div ng-repeat="template in templates">
<ng-include src="template.url"></ng-include>
</div>
Run Code Online (Sandbox Code Playgroud)
所以这里的模板是一个对象数组,其中包含你想在main.html文件中一次加载的其他模板的所有url.
简单.将它们全部创建为ng-template块:
<script type="text/ng-template" id="app/access/partials/a1.html">
Content of the template.
</script>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2099 次 |
最近记录: |