Angularjs $templateCache、$templateRequest、ngInclude一起玩得很好(er)

Angularjs $templateCache、$templateRequest、ngInclude一起玩得很好(er),angularjs,angularjs-ng-include,Angularjs,Angularjs Ng Include,我试图在第一个页面查看时获取我的所有部分,以便在应用程序查看期间不会下载html 一种方法是在index.html中使用模板。 我认为.js文件不适合html代码和同样的问题 就像在index.html中一样 我想做的是,在不同的文件中有模板,这样我就可以保持我的模块结构并将它们预加载到索引中 这就是我现在拥有的 var cmsAppFirstRun = function ($templateCache, $templateRequest, $rootScope) { $templ

我试图在第一个页面查看时获取我的所有部分,以便在应用程序查看期间不会下载html

一种方法是在
index.html
中使用模板。
  • 我认为
    .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});
      }
    }
})
这样,路线中的所有模板都将在第一次运行时加载


编辑:我使用的是使东西在
angular.run()
block中看起来有点不同。此处尚未处理嵌套视图

angular.forEach($state.get(), function(state){
            if(state.templateUrl){
                $http.get(state.templateUrl, {cache: $templateCache});
            }
        });

编辑2:我错过了$templateRequest,它可以是
angular.run()
block中html模板的路径

 $templateRequest('views/cart/modal-confirm-continue-printing.html');
 $templateRequest('views/cart/modal-confirm-trash.html');


编辑3:由于我使用grunt构建应用程序,我发现使用grunt可以自动完成此过程。

不确定是否可以帮助您,但在我的项目中,我曾经生成一个js文件,其中包含所有html文件,如“$templateCache.put()”指令。

我使用grunt,后来遇到了一些具有相同功能的脚本。我可能也会用我的发现更新答案。$templateRequest就是针对这种情况制定的。这绝对是最好的选择。我已经切换到使用我可以自动处理过程和在应用程序启动时发出更少请求的地方
angular.forEach($state.get(), function(state){
            if(state.templateUrl){
                $http.get(state.templateUrl, {cache: $templateCache});
            }
        });
 $templateRequest('views/cart/modal-confirm-continue-printing.html');
 $templateRequest('views/cart/modal-confirm-trash.html');