我有一个使用 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();
}
}
文档:
附带说明一下,我觉得您想要从服务器重新获取模板很奇怪。
关于AngularJs ui-router 重载模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34589604/