我在AngularJS中缓存部分有问题。
在我的HTML页面,我有:
<body>
<div ng-view></div>
<body>
我的偏导数被载入的地方。
当我改变HTML代码在我的部分,浏览器仍然加载旧数据。
有什么解决办法吗?
我在AngularJS中缓存部分有问题。
在我的HTML页面,我有:
<body>
<div ng-view></div>
<body>
我的偏导数被载入的地方。
当我改变HTML代码在我的部分,浏览器仍然加载旧数据。
有什么解决办法吗?
当前回答
我发现HTTP拦截器方法工作得非常好,并允许额外的灵活性和控制。此外,您可以为每个产品版本使用一个发布散列作为buster变量来缓存bust。
下面是使用Date的dev缓存破坏方法。
app.factory('cachebustInjector', function(conf) {
var cachebustInjector = {
request: function(config) {
// new timestamp will be appended to each new partial .html request to prevent caching in a dev environment
var buster = new Date().getTime();
if (config.url.indexOf('static/angular_templates') > -1) {
config.url += ['?v=', buster].join('');
}
return config;
}
};
return cachebustInjector;
});
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('cachebustInjector');
}]);
其他回答
如果你谈论的是用于模板缓存而不需要重新加载整个页面的缓存,那么你可以通过如下方式清空它:
.controller('mainCtrl', function($scope, $templateCache) {
$scope.clearCache = function() {
$templateCache.removeAll();
}
});
在标记中:
<巴顿ngk -click=“clearCache()”>清廉缓存</按钮>
并按此按钮清除缓存。
如果你正在使用UI路由器,那么你可以使用装饰器和更新$templateFactory服务,并将查询字符串参数附加到templateUrl,浏览器将始终从服务器加载新模板。
function configureTemplateFactory($provide) {
// Set a suffix outside the decorator function
var cacheBust = Date.now().toString();
function templateFactoryDecorator($delegate) {
var fromUrl = angular.bind($delegate, $delegate.fromUrl);
$delegate.fromUrl = function (url, params) {
if (url !== null && angular.isDefined(url) && angular.isString(url)) {
url += (url.indexOf("?") === -1 ? "?" : "&");
url += "v=" + cacheBust;
}
return fromUrl(url, params);
};
return $delegate;
}
$provide.decorator('$templateFactory', ['$delegate', templateFactoryDecorator]);
}
app.config(['$provide', configureTemplateFactory]);
我相信你可以通过装饰$routeProvider中的"when"方法来达到同样的效果。
在@Valentyn回答的基础上,这里有一种方法可以在ng-view内容发生变化时自动清除缓存:
myApp.run(function($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function() {
$templateCache.removeAll();
});
});
这是Chrome的另一个选项。
按F12打开开发人员工具。然后资源>缓存存储>刷新缓存。
我喜欢这个选项,因为我不需要像其他答案那样禁用缓存。
我发布这篇文章只是为了涵盖所有的可能性,因为其他的解决方案都不适合我(他们由于角引导模板依赖而抛出错误)。
当你在开发/调试一个特定的模板时,你可以确保它总是通过在路径中包含一个时间戳来刷新,就像这样:
$modal.open({
// TODO: Only while dev/debug. Remove later.
templateUrl: 'core/admin/organizations/modal-selector/modal-selector.html?nd=' + Date.now(),
controller : function ($scope, $modalInstance) {
$scope.ok = function () {
$modalInstance.close();
};
}
});
注意templateUrl变量中最后的?nd=' + Date.now()。