Question

I have noticed that from time to time I'll make a change to one of the templates within my AngularJS application and that at runtime, the change won't be visible. Rather, I'll have to refresh the application and if that fails, go to the path of the template itself and refresh it in order to see this change.

What's the best way to prevent caching of these templates like this? Ideally, I'd like them to be cached during the current use of the Angular application, but that the next time I load the page, they retrieve the latest and greatest templates without having to manually refresh.

I'm using ui-router if that makes any difference here. Thanks!

Was it helpful?

Solution

You can use a decorator and update UI Router's $templateFactory service to append a suffix to templateUrl

function configureTemplateFactory($provide) {
    // Set a suffix outside the decorator function 
    var cacheBuster = 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=" + cacheBuster;
            }

            return fromUrl(url, params);
        };

        return $delegate;
    }

    $provide.decorator('$templateFactory', ['$delegate', templateFactoryDecorator]);
}

app.config(['$provide', configureTemplateFactory]);

OTHER TIPS

Above solution was great and was not working for template urls

function templateUrl: function($stataParams) { return '/serverUrl?id=' + $stataParams.id + '&cid=' + $stataParams.cid; }

fixed by

function templateFactoryDecorator($delegate) {
    var fromUrl = angular.bind($delegate, $delegate.fromUrl);
    $delegate.fromUrl = function (url, params) {
        if (url !== null && angular.isDefined(url)) {
            if (typeof url == 'function') {
                url = url.call(url, params);
            }
            if (angular.isString(url)) {
             url += (url.indexOf("?") === -1 ? "?" : "&");
             url += "v=" + Date.now().toString();
             }
         }

         return fromUrl(url, params);
     };

     return $delegate;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top