One of my partials is a report—a static list of names and dates that's just for viewing and printing.
Since it's more efficient to render the report server-side, my API sends back HTML for the report request instead of JSON. The template URL in the report route is that API call:
.when('/report', {
templateUrl: 'api/report',
});
The report shows up at the right URL, but when I go to another route and change the data, the report isn't reloaded. I tried setting the no-cache header in the API response, but it didn't have an effect.
Is there a best practice for forcing Angular to refresh certain templates?
Angular has an internal cache for templates, serviced by the $templateCache service. After a template is fetched from the server, its reference and content is cached inside Angular, and used instead of re-requesting it from the server.
The $templateCache service has two relevant methods for your situation - .remove("templateUrl") and .removeAll(). In the situation where you want to remove a specific template, you can obviously use the .remove(templateUrl) method.
This can be done in either the controller (which, when loaded, will have already loaded the template), or in a more general event, such as the global $routeChangeSuccess event. For example:
module.run(["$templateCache", function ($templateCache) {
$rootScope.$on("$routeChangeSuccess", function (event, current, previous) {
$templateCache.remove(current.$$route.templateUrl);
});
}]);
While this will clear the specific entry in the Angular cache, you still need to make sure your server is setting the appropriate headers on the template's response so that when it is requested from the server, the browser doesn't cache it.
In a different scenario, if you never wanted any template to be cached within Angular, you could bind the global $includeContentLoaded and $routeChangeStart events and call $templateCache.removeAll() to make sure no templates are ever cached.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With