AngularJS TemplateCache

AngularJS TemplateCache

本文关键字:TemplateCache AngularJS      更新时间:2024-02-25

我正在尝试使用gulp-angular-templatecache生成模板缓存,并将其与Angular脚本组合到一个JS文件中。

吞咽任务:

gulp.task('generatetemplatecache', function () {
    return gulp.src(['dev/app/**/*.tpl.html'])
    .pipe(minifyHTML({quotes: true}))
    .pipe(templateCache({ module:'templateCache', standalone:true }))
    .pipe(gulp.dest('public/app'));
});

这基本上就是输出的样子:

var app = angular.module("app",['templateCache']);
angular.module("templateCache", []).run(["$templateCache", function($templateCache) {$templateCache.put("test.tpl.html","<!DOCTYPE html><html lang='"en'"><head><meta charset='"UTF-8'"><title>My Title</title></head><body></body></html>");
$templateCache.put("layout/popover.tpl.html","<h3 class='"popover-title'">Click</h3><div class='"popover-content'"><table style='"width:600px'" class='"table'"><tr ng-repeat='"customer in customers'"><td>{{customer.name}}</td><td>{{customer.street}}</td></tr></table>ss</div>");

但问题是,我发现它不是从templatecache加载的。每当angular需要模板时,它仍然会抓取原始模板html文件。如果该html文件不可用,那么它将无法显示。

为什么它不起作用?我做错了什么?模板缓存中的url是相对于index.html还是相对于域的根?

创建模板文件时,需要检查的一件事是确保路径正确。

例如,在我的应用程序中,我所有的源代码都是这样组织的:

modules
   |---user
      |---user-controller.js
      |---user-service.js
      |---user.html
   |---navigation
      |---navigation-controller.js
      |---header.html
      |---footer.html

因此,在我的路由器或templateUrl属性的任何指令中,我引用我的HTML文件,如:

modules/user/user.html

所以,也就是说,在我的Gulpfile中,当我创建templateCache文件时,我指定了一个"module"的根,这样每个文件在templateCache中都有一个等于这个路径的键。例如:

gulp.task('templates', function () {
    gulp.src('./app/modules/**/*.html')
        .pipe(angularTemplatecache('templates.js', {
            standalone: true,
            root: "modules"
        }))
        .pipe(gulp.dest('./app/templates'));
});

如果所有其他配置问题都是正确的(即,您正确地加载了templates.js文件,您将其作为应用程序的模块依赖项包含在内),则此路径问题可能是您在加载它们时遇到困难的原因。

您还可以使用另一个gull插件,它可以读取您的路由、指令,并用templateUrl中引用的模板替换templateUrl。

src
+-hello-world
  |-hello-world-directive.js
  +-hello-world-template.html

hello-world-directive.js:

angular.module('test').directive('helloWorld', function () {
    return {
        restrict: 'E',
        // relative path to template
        templateUrl: 'hello-world-template.html'
    };
});

hello-world-template.html:

<strong>
    Hello world!
</strong>

gullfile.js:

var gulp = require('gulp');
var embedTemplates = require('gulp-angular-embed-templates');
gulp.task('js:build', function () {
    gulp.src('src/scripts/**/*.js')
        .pipe(embedTemplates())
        .pipe(gulp.dest('./dist'));
});

gullowangular嵌入模板将生成以下文件:

angular.module('test').directive('helloWorld', function () {
    return {
        restrict: 'E',
        template:'<strong>Hello world!</strong>'
    };
});