AngularJs ui-router 重载模板

标签 angularjs angular-ui-router

我有一个使用 ui-router 进行路由的 angularjs 项目。
我正在使用 $state.reload()重新加载当前状态,它工作得很好,只是在我的开发系统中我想要 $state.reload()还可以重新加载 html 模板以反射(reflect)新的更改,而无需重新加载整个页面。

有没有黑客或选项可以做到这一点?

更新 :

Chris T 的解决方案几乎奏效,但我有 templateFactoryDecorator女巫向模板 url 添加了一个缓存破坏者。

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

所以
$templateCache.remove($state.current.templateUrl);

没有用,我不得不使用
$templateCache.removeAll();

它并不理想,但对于开发环境来说还可以。

最佳答案

在内部,UI-Router leverages the $templateCache service以避免重新获取模板。调用前$state.reload() , 清除要从服务器重新获取的模板。

假设您想从 Controller 执行此操作:

function MyController($scope, $templateCache, $state) {
    $scope.reload = function() {
        $templateCache.remove("/path/to/template.html");
        $state.reload();
    }   
}

文档:
  • $templateCache
  • $cacheFactory

  • 附带说明一下,我觉得您想要从服务器重新获取模板很奇怪。

    关于AngularJs ui-router 重载模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34589604/

    相关文章:

    AngularJS 指令 transclude 部分绑定(bind)

    javascript - 仅当在 Angular 中找到匹配项时才显示搜索结果(Ng-Repeat)

    angularjs - Angular ui.router 动态 ui-sref

    javascript - 路由重定向到Angular问题中的其他链接

    angularjs - 没有 urlRouterProvider.otherwise 的 ui 路由

    javascript - Angular/karma : Error: [$injector:nomod] Module 'module' is not available

    javascript - 当对象唯一时将其推送到数组

    javascript - 如何测试仅用作模板的指令

    javascript - 如何在 Angular 2 的 ui-router 中使用 `otherwise`?

    javascript - ui-sref 被阻止访问 Controller 数据或 View