使用 ui-router 在 AngularJS 中禁用模板缓存 [英] Disable template caching in AngularJS with ui-router

查看:36
本文介绍了使用 ui-router 在 AngularJS 中禁用模板缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,我会不时对 AngularJS 应用程序中的模板之一进行更改,但在运行时,更改将不可见.相反,我必须刷新应用程序,如果失败,请转到模板本身的路径并刷新它以查看此更改.

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.

防止像这样缓存这些模板的最佳方法是什么?理想情况下,我希望在当前使用 Angular 应用程序期间缓存它们,但下次我加载页面时,它们会检索最新和最好的模板,而无需手动刷新.

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.

如果这对这里有任何影响,我正在使用 ui-router.谢谢!

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

推荐答案

您可以使用装饰器并更新 UI Router 的 $templateFactory 服务以将后缀附加到 templateUrl

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]);

这篇关于使用 ui-router 在 AngularJS 中禁用模板缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆