问题
I have an Angular application which shows people profile images(loaded from a server) and has an option to change it.
When the application loads the first time, the image is displayed properly. I call a web service to change the image on a server. The problem is even after changing the image on remote server, the image on the browser is not reflecting the change even on refreshing the page.
I tried using the meta tags to disable caching but it's not working for me.
The image changes on the browser only after I delete the browser cache. How can I solve this?
Example Flow based on Comments:
- Initial path:
http://server_path/image_name.jpg
- Call web service and change the image (NOTE: path of image does not change. Only the image itself is replaced)
- Refresh the page on browser
PROBLEM: Changed image not reflected.
回答1:
If it is getting cached in the browser, you can force every request for the image to use a different URL, and so always request the server, by appending a different query string to it, say equal to the current number of milliseconds since 1970. A short custom directive is probably a good way:
app.directive('noCacheSrc', function($window) {
return {
priority: 99,
link: function(scope, element, attrs) {
attrs.$observe('noCacheSrc', function(noCacheSrc) {
noCacheSrc += '?' + (new Date()).getTime();
attrs.$set('src', noCacheSrc);
});
}
}
});
that is used as
<img no-cache-src="http://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Swallow_flying_drinking.jpg/320px-Swallow_flying_drinking.jpg">
(much as ngSrc
would be used). You can see a demo in this plunker.
Note, the directive as written will probably not work if the src
already has a query string. It might need to test for the presence of a ?
and adjust how it behaves (i.e. if there is a ?
, add &
+ seconds instead).
Edit: simplified by just using one directive.
来源:https://stackoverflow.com/questions/23285280/angular-changed-image-in-server-not-reflecting-in-view