AngularJS中的templateRequest后备 [英] templateRequest fallback in AngularJS
问题描述
我有以下服务,可用于在AngularJS应用程序中为状态提取模板:
I have the following service I use to pull out a template for a state in my AngularJS application:
.factory('templateService', ['$templateRequest', '$translate', function($templateRequest, $translate) {
return {
getTemplate: function(stateParams, url) {
return $templateRequest( 'partials/' + url + '-' + ( $translate.use() ? $translate.use() : $translate.preferredLanguage ) + '.html');
}
}
}]);
这是使用中的
.state('section3',
{
parent: 'maincontent',
url: '/section3',
views: {
'header@maincontent': {
templateUrl: 'partials/section3/_header.html'
},
'content@maincontent': {
templateProvider: function($stateParams, templateService) {
return templateService.getTemplate($stateParams, '/section3/_content');
}
}
}
})
从服务中可以看到,我从$ translate模块传递了一些额外的信息来加载特定于语言的模板,但是,如果该模板不存在,那只是一个错误.
As you can see from the service, I pass some extra information from the $translate module to load a language-specific template, however if the template doesn't exist it just an error.
如果模板不存在,我想做的就是捕获错误,然后加载回退.
What I want to do is catch the error if the template doesn't exist and then load in a fallback instead.
类似的东西:
var request = $templateRequest( 'partials/' + url + '-' + ( $translate.use() ? $translate.use() : $translate.preferredLanguage ) + '.html');
if(request)
return request;
else
return $templateRequest( 'partials/' + url + '-fallback.html');
如何检查$ templateRequest是否成功?由于上述代码无法立即使用.
How do I check if $templateRequest was successful or not? As the above code doesn't work out of the box.
我发现由于$ templateRequest是一个Promise,我可以通过以下方式捕获错误:
I've found that because $templateRequest is a Promise, I can catch the error with:
.factory('templateService', ['$templateRequest', '$translate', '$compile', function($templateRequest, $translate, $compile) {
return {
getTemplate: function(stateParams, url) {
$templateRequest('partials' + url + '-' + ( $translate.use() ? $translate.use() : $translate.preferredLanguage ) + '.html')
.then(function(response){
return $compile(response);
})
.catch(function(){
return $templateRequest('partials' + url + '-en.html');
});
}
}
}]);
尽管如此,即使使用$ compile,也意味着返回的模板没有用于 then
或 catch
.所以现在这些模板根本就没有用...
However that being said, even using $compile, means that the returned template isn't being used for either the then
or the catch
. So now the templates aren't getting used at all...
推荐答案
我认为您缺少 templateService.getTemplate
的回报.
.factory('templateService', ['$templateRequest', '$translate', '$compile', function($templateRequest, $translate, $compile) {
return {
getTemplate: function(stateParams, url) {
return $templateRequest('partials' + url + '-' + ( $translate.use() ? $translate.use() : $translate.preferredLanguage ) + '.html')
.then(function(response){
return $compile(response);
})
.catch(function(){
return $templateRequest('partials' + url + '-en.html');
});
}
}
}]);
这篇关于AngularJS中的templateRequest后备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!