AngularJS TemplateCache

时间:2015-02-22 06:56:49

标签: javascript angularjs gulp

我正在尝试使用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还是域的根?

2 个答案:

答案 0 :(得分:2)

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

例如,在我的应用程序中,我的所有源代码都以这种方式组织:

modules
   |---user
      |---user-controller.js
      |---user-service.js
      |---user.html

   |---navigation
      |---navigation-controller.js
      |---header.html
      |---footer.html

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

modules/user/user.html

那就是说,在我创建templateCache文件时,在我的Gulp文件中,我指定了一个&#39; modules&#39;这样每个文件都被赋予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文件,将其作为模块依赖项包含在您的应用中),这个路径问题可能就是您在加载它们时遇到问题的原因< / p>

答案 1 :(得分:0)

您还可以使用另一个gulp plugin,它可以读取您的路线,指令,并将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>'
    };
});
相关问题