【问题标题】:$templateCache, $templateRequest, ngInclude play nice(er) together$templateCache, $templateRequest, ngInclude 一起玩好(er)
【发布时间】:2015-05-18 09:34:25
【问题描述】:

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

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

<script type="text/ng-template" id="templateId.html">
  <p>This is the content of the template</p>
</script>
  • 这样你就有超过5个模板index.html文件变成 难以管理并破坏了项目的模块结构。

另一种方法是在.js 文件中包含html,很可能在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>

有没有更性感、更棱角分明的方式来做到这一点?

【问题讨论】:

    标签: angularjs angularjs-ng-include


    【解决方案1】:

    stack answers 中发现了一些使用$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 Router,所以在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 用于自动化此过程。

    【讨论】:

    • $templateRequest 就是针对这种情况而提出的。绝对是这里的最佳选择。
    • 我已改用npmjs.com/package/grunt-angular-templates,我可以在其中自动化流程并减少应用启动时的请求
    【解决方案2】:

    不确定是否可以帮助您,但在我的项目中,我使用gulp-ngtemplate 生成了一个包含所有 html 文件作为“$templateCache.put()”指令的 js 文件。

    【讨论】:

    • 我使用 grunt 并且从那以后遇到了一些具有相同功能的脚本。可能也会用我的发现更新答案。
    猜你喜欢
    • 2015-08-28
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多