【问题标题】:How to put content of $templateCache.put(...) into html file instead of embedding Html into Javascript?如何将 $templateCache.put(...) 的内容放入 html 文件而不是将 Html 嵌入 Javascript?
【发布时间】:2016-11-16 23:54:36
【问题描述】:

当你有一个文件 app.js 和许多模块时,像下面的代码 sn-p 在 JavaScript 中嵌入 HTML 是不可维护的。

app.js

app.config(['$routeProvider', function($routeProvider){
  $routeProvider.when('/first',{
    templateUrl: 'partial/first.html',
    controller: 'FirstCtrl' 
  });
}]).run(function($templateCache){
     $templateCache.put('partial/first.html', '<p>Hundred lines of Html</p>');
    });

是否可以将这 100 个 LoC 从 $templateCache.put(...) 迁移到 Html 文件中,就像我们使用 templateUrl 而不是模板一样?或者建议另一种方法来实现这一点,因为我正在失去对代码的控制。我想使用 $templateCache 进行快速检索。

【问题讨论】:

    标签: javascript html angularjs angular-template angular-templatecache


    【解决方案1】:

    您应该使用构建脚本,例如用gulp 做这种事情。有一个名为 angular-template-cache 的 npm 模块可以满足您的需求。

    var angularTemplateCache = require('gulp-angular-templatecache');
    
    gulp.task('compile:templates', () =>
        gulp.src('/src/**/*.html')
            .pipe(angularTemplateCache('templates.js'))
            .pipe(gulp.dest('/dist'))
    );
    

    此 gulp 任务将创建一个文件 /dist/templates.js,其中包含 $templateCache.put 用于 src 目录下的每个 html 文件。您可以将这部分与缩小、缓存清除等一起作为构建过程的一部分。

    【讨论】:

    • 能否请您在答案中添加代码,以便我们了解如何实现解决方案。
    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 2021-08-31
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多