繁体   English   中英

AngularJS TemplateCache

[英]AngularJS TemplateCache

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

gulp任务:

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加载。 每当有角度需要模板时,它仍会获取原始模板的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

因此,可以这么说,当我创建模板缓存文件时,在我的Gulp文件中,我指定了“模块”的根目录,以便为每个文件赋予模板缓存中与此路径相同的键。 如:

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

此路径问题可能是为什么如果所有其他配置问题都正确的话,则在加载它们时会遇到麻烦(即,您正确加载了templates.js文件,并将其作为模块依赖项包含在您的应用中)

您还可以使用另一个gulp 插件 ,该插件可以读取您的路线,指令,并将templateUrl替换为templateUrl中引用的模板。

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

你好,世界directive.js:

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

你好,世界template.html:

<strong>
    Hello world!
</strong>

gulpfile.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'));
});

gulp-angular-embed-templates将生成以下文件:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM