更新缓存的模板

8

我使用templateUrl,它非常好用!

app.directive('myDir', function() {
    return {
        templateUrl: 'partials/directives/template.html'
    };
};

然而,当我修改这些模板时,它们并没有更新。在开发过程中,这不是一个大问题,因为我知道哪些已经更新了,可以手动清除缓存。

但是我无法清除所有用户的缓存。有没有办法做到这一点?比如使用CACHE-CONTROL元标记或类似的东西?


AngularJS的templateCache在刷新浏览器时会被清除。如果您仍然得到旧模板,那是因为浏览器缓存了部分内容。正如您所说,您需要检查缓存标头并进行调整。 - Chandermani
我不确定要添加什么。我应该在index.html中添加“无缓存”吗?还是在每个部分中都添加它?我还注意到服务器正在发送ETAG元数据,为什么浏览器(chrome)没有使用它呢 :(? - Snæbjørn
你找到了解决这个问题的方法吗?如果有,请分享一下。 - Troels
是的,我犯了傻瓜错误,禁用了缓存 :/ app.config(function ($httpProvider) { $httpProvider.defaults.headers.get = { 'Cache-Control': 'no-cache' }; }); - Snæbjørn
2个回答

2
据我所见,您有两个选项 -
  1. use $cacheFactory service to remove the old cache After a template has been fetched, Angular caches it in the default $templateCache services

    // Please note that $cacheFactory creates a default key '$http'
    
    var cache = $cacheFactory.get('$http');
    
    // The remove() function removes a key-value pair from the cache, 
    // if it’s found. If it’s not found, then it just returns undefined.
    
    cache.remove(your url);
    
  2. use file versioning rename the file with each change - i.e. if your first version of the file is template-1.0.1.html, when you make some code changes rename it to template-1.0.2.html and so on. This way the new file will be downloaded each time you make some changes.


谢谢,但是难道没有更好的方法吗?你提供的两种解决方案都是试图修复症状而非原因。我正在寻找的解决方案是浏览器知道文件已经更新,然后重新获取它。例如,使用元ETAG。 - Snæbjørn
还有另一种方法-将您的模板存储在js文件中。它们不会被Angular缓存。 - Mikhail Kopylov
如果我们正在提到这些“技巧”,那么我记得一个旧方法,您不需要更改模板文件的名称,但是需要更改请求。 因此,它看起来像这样:templateUrl:'tplFile.html?v=20150503 - george007

2

一个快速而不太完美的解决方案是在$httpProvider中禁用缓存。

app.config(function ($httpProvider) {
    $httpProvider.defaults.headers.get = {
        'Cache-Control': 'no-cache'
    };
});

我不建议这样做,但它确实有效。


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