Disable template caching in AngularJS with ui-rout

2019-01-14 07:48发布

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!

2条回答
SAY GOODBYE
2楼-- · 2019-01-14 08:33

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]);
查看更多
我只想做你的唯一
3楼-- · 2019-01-14 08:38

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;
}
查看更多
登录 后发表回答