我正在尝试在第一页查看时获取我的所有部分,以便在查看应用程序期间不会下载任何 html。
一种方法是在 index.html
中拥有模板。
<script type="text/ng-template" id="templateId.html">
<p>This is the content of the template</p>
</script>
- 这样,您有超过 5 个模板
index.html
文件变成无法管理并破坏项目的模块结构。
另一种方法是将html放在.js
文件中,很可能是app.js
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
- 我认为
.js
文件不是 html 代码的地方,再次出现同样的问题就像在index.html
中一样.
我想做的是在不同的文件中拥有模板,这样我就可以保持我的模块结构并将它们预加载到索引上。
这就是我现在所拥有的。
var cmsAppFirstRun = function ($templateCache, $templateRequest, $rootScope) {
$templateRequest('views/common/top-bar.html').then(function (response) {
$templateCache.put('top.bar', response);
$rootScope.templatesDone = true;
});
};
angular.module('cmsApp').run(cmsAppFirstRun);
和 html
<div ng-include="'top.bar'" ng-if="$root.templatesDone"></div>
有没有更性感、更有棱角的方法来做到这一点?
在堆栈答案中使用$http
和$route
发现了一些技术。
我认为最吸引人的是
angular.module('MyApp', [])
.run(function ($templateCache, $route, $http) {
var url;
for(var i in $route.routes)
{
if (url = $route.routes[i].templateUrl)
{
$http.get(url, {cache: $templateCache});
}
}
})
这样,路由中的所有模板都会在首次运行时加载。
编辑:我正在使用UI路由器,所以angular.run()
块中看起来有点不同。此处尚未处理嵌套视图。
angular.forEach($state.get(), function(state){
if(state.templateUrl){
$http.get(state.templateUrl, {cache: $templateCache});
}
});
编辑2:我错过了$templateRequest可以作为angular.run()
块中html模板的路径。
$templateRequest('views/cart/modal-confirm-continue-printing.html');
$templateRequest('views/cart/modal-confirm-trash.html');
编辑3:由于我使用grunt构建应用程序,因此我发现 https://www.npmjs.com/package/grunt-angular-templates 自动化此过程很有用。
不确定是否可以帮助您,但在我的项目中,我使用 gulp-ngtemplate 生成一个包含所有 html 文件的 js 文件作为"$templateCache.put()"指令。