首页 > 解决方案 > 输入字段和绑定数据的 Angularjs 缓存问题

问题描述

我在 angularjs 中面临缓存问题,我已经尝试过

 <meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0">
 <meta http-equiv="expires" content="0">
 <meta http-equiv="pragma" conten="no-cache">

并在请求标头中

    headers : {
                'cache': 'false',
                'Cache-Control': 'no-cache',
                'Cache-Control': 'private',
                'Cache-Control': 'must-revalidate',
                'Cache-Control': 'max-age=0'
            },

如果我修改了第 1 页中的输入,稍后如果我再次返回第 1 页,则修改后的输入有时会从缓存数据中获取值。

如何解决angularjs中的这个缓存问题?

标签: angularjscachinghttp-headersbrowser-cacherequest-headers

解决方案


您可以将版本添加到要防止缓存的模板。

要在 Angular js 中做到这一点,简单和最好的方法如下。

  1. 创建服务

app.factory('preventTemplateCache',function(){
  var threeDigitRandom = Math.floor(Math.random() * 999);
  return {
    'request': function(config) {
      if (config.url.indexOf('templates') !== -1) {
        config.url = config.url + '?v=' + threeDigitRandom;
      }
      return config;
    }
  }
})

这里 config.url 是你的模板路径(.html)

  1. 使用 $httpProvider.interceptors 调用工厂,如下所示

app.config(function($httpProvider) {
    $httpProvider.interceptors.push('preventTemplateCache');
  });

这在所有情况下都非常有效,可以防止 Angular js 应用程序中的模板缓存。


推荐阅读