Angular模板缓存未生效

21

我有一个使用gulp和angular的项目。我想要点击一个按钮,弹出包含HTML内容的对话框。

在 build.js 文件中,我有以下代码:

gulp.task('templates', function() {
  gulp.src(['!./apps/' + app + '/index.html', './apps/' + app + '/**/*.html'])
    .pipe(plugins.angularTemplatecache('templates.js', {
      standalone: true,
      module: 'templates'
    }))
    .pipe(gulp.dest(buildDir + '/js'));
});

在我的app.js文件中,我有以下代码:

.controller('PopupCtrl', function($scope, ngDialog) {
  $scope.clickToOpen = function () {
      ngDialog.open({ 
        template: 'templates/popup.html'
      });
  };
})

点击按钮时出现错误:

GET http://mylocalhost:3000/templates/popup.html 404 (Not Found) 

我的 templates.js 文件包含:

angular.module("templates", []).run(["$templateCache", function($templateCache) {
$templateCache.put("templates/popup.html", "my html") ...etc
为什么模板缓存不认识对templates/popup.html的调用,而是显示缓存中的内容,而不是查看404的URL?
只是想说我已经尝试过了,我手动将模板文件复制到它所在的目录中,它找到了。但这并不是解决办法,因为我希望它从缓存中取出。谢谢。
4个回答

26

你还需要将templates模块作为你的模块依赖进行指定。例如:

angular.module('myApp', ['templates', 'ngDialog'])

希望这可以帮到你。


谢谢!你救了我的一天!(即使是在2018年,四年后:)) - Gondy

18

这个答案是给其他可能遇到这个问题的人的,但他们确定已经像接受的答案所说包含了依赖项:

确保验证你正在使用的“key”匹配。在我的情况下,以下情况发生:

$templateCache.put('/someurl.html', 'some value');

但是它正在寻找'someurl.html'。一旦我更新了我的代码:

$templateCache.put('someurl.html', 'some value');

一切开始正常运作。


2
我也遇到过。该死的肯定! - tmanion
1
大小写也很重要! - Burjua
1
我使用gulp生成'$templateCache',路径从'templatesUrl'引用的实际文件夹的子文件夹开始。这帮助我找出了问题所在。 - jsbisht
1
我刚遇到了这个问题,结果发现URL前面有一个空格。 - Patrick McElhaney
在我的情况下,我有一个拦截器将应用程序版本附加到URL以进行缓存破坏。因此,如果URL已加载到$templateCache中,我必须更改我的拦截器以不执行该操作。 - adam0101

1

还有一种方法可以消除对$templatecache的依赖。

您可以使用gulp插件,它可以读取您的路由、指令,并将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>

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

1
我两分钱的建议(因为我也曾在这方面碰壁):
1)确保你的主模块中有一个依赖项(如果你为模板创建了一个单独的模块)。
2)确保在模板 URL 中处理了前导 \。
3)确保文件名中使用的文本大小写与模板 URL 中使用的大小写匹配。(是的,这个要注意)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接