$ templateCache,$ templateRequest,ngInclude一起玩好(呃)

Ter*_*for 6 angularjs angularjs-ng-include

我试图在第一页视图中获取所有部分内容,以便在应用程序查看期间不下载任何html.

一种方法是使用模板index.html.

<script type="text/ng-template" id="templateId.html">
  <p>This is the content of the template</p>
</script>
Run Code Online (Sandbox Code Playgroud)
  • 这种方式是你有超过5个模板index.html文件变得难以管理并打破了项目的模块结构.

另一种方法是将html保存在.js文件中,最有可能在文件中app.js

myApp.run(function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});
Run Code Online (Sandbox Code Playgroud)
  • 我认为.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);
Run Code Online (Sandbox Code Playgroud)

和HTML

<div ng-include="'top.bar'" ng-if="$root.templatesDone"></div>
Run Code Online (Sandbox Code Playgroud)

这样做是否有更性感,更有棱角的方式?

Ter*_*for 2

找到了一些使用$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});
      }
    }
})
Run Code Online (Sandbox Code Playgroud)

这样,路线中的所有模板都会在第一次运行时加载。


编辑:我正在使用UI Router,所以块中的东西看起来有点不同angular.run()。此处尚未处理嵌套视图。

angular.forEach($state.get(), function(state){
            if(state.templateUrl){
                $http.get(state.templateUrl, {cache: $templateCache});
            }
        });
Run Code Online (Sandbox Code Playgroud)

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

 $templateRequest('views/cart/modal-confirm-continue-printing.html');
 $templateRequest('views/cart/modal-confirm-trash.html');
Run Code Online (Sandbox Code Playgroud)

编辑 3:由于我使用 grunt 构建应用程序,我发现https://www.npmjs.com/package/grunt-angular-templates对于自动化此过程很有用。