Updating server generated template in AngularJS

One of my particulars is a report - a static list of names and dates that is for viewing and printing only. In the meantime, there is no need to worry about it.

Since it is more efficient to render the report server, my API sends back HTML to request the report instead of JSON. The template url in the report route is an API call:

.when('/report', {
    templateUrl: 'api/report',
});

      

The report is displayed at the correct URL, but when I change the route and change the data, the report does not reload. I tried to set the header no-cache

in the API response, but it had no effect.

Is there a better way to get Angular to update certain templates?

+3


source to share


1 answer


Angular has an internal cache for templates served by the service $templateCache

. After the template is loaded from the server, its link and content are cached inside Angular and used instead of re-requesting it from the server.

The service $templateCache

has two suitable methods for your situation - .remove("templateUrl")

and .removeAll()

. In a situation where you want to remove a specific template, you can obviously use the method .remove(templateUrl)

.

This can be done either in the controller (which has already loaded the template when loaded), or more generally, such as a global event $routeChangeSuccess

. 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 Angular cache entry, you still need to make sure that your server sets the appropriate headers in the template response so that when it is requested from the server, the browser does not cache it.

In another scenario, if you never want to any template has been cached in Angular, you could tie the global events $includeContentLoaded

and $routeChangeStart

and call $templateCache.removeAll()

to ensure that the templates are never cached.

+3


source







All Articles