1

当您有一个文件 app.js 和许多模块时,像下面的代码片段那样在 JavaScript 中嵌入 HTML 是不可维护的。

应用程序.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进行快速检索。

4

1 回答 1

2

您应该使用构建脚本,例如使用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目录下的每个 html 文件src。您可以将这部分与缩小、缓存清除等一起作为构建过程的一部分。

于 2016-10-24T10:57:34.047 回答