我以这种方式定义状态:
var parentStates = [
{state : 'home', url: '/home', template: 'home.html'},
{state : 'about', url: '/about', template: 'about.html'},
{state : 'contact', url: '/contact', template: 'contact.html'},
{state : 'home.data', url: '', template: 'data.html'},
{state : 'about.data', url: '', template: 'data.html'},
{state : 'contact.data', url: '', template: 'data.html'}
];
$urlRouterProvider.otherwise("/main/home");
$stateProvider
.state("main", { abtract: true, url:"/main",
views: {
"viewA": {
templateUrl:"main.html"
}
}
});
parentStates.forEach(function(value){
$stateProvider
.state("main." + value.state, {
url: value.url,
views: {
"": {
templateUrl: value.template
}
},
})
});
我想写一个
'decorator'
,用于根据'templateUrl'
(如上所示, View 的名称为空)来设置 View 的名称。这是装饰器的代码:
$stateProvider.decorator('views', function (state, parent) {
var result = {},
views = parent(state);
// Don't touch the 'main state'
if (state.name === "main") {
return views;
}
angular.forEach(views, function (config, name) {
if(config.templateUrl=='data.html'){
result[name] = 'viewC@main';
}
else{
result[name] = 'viewB@main';
}
});
return result;
});
当然,这是行不通的。我有点迷路了。
最佳答案
有a working plunker
你快到了。让我们简化一下状态定义(因为我们不需要嵌套的view对象,我们将在以后创建它):
parentStates.forEach(function(value) {
$stateProvider
.state("main." + value.state, {
url: value.url,
templateUrl: value.template,
})
});
这将是装饰器:
$stateProvider.decorator('views', function(state, parent) {
var result = {},
views = parent(state);
// some example when to not inject resolve
if (state.name === "main") {
return views;
}
angular.forEach(views, function(config, name) {
// the super child template
if(config.templateUrl === 'data.html'){
result['viewC@main'] = config;
}
else{
result['viewB@main'] = config;
}
});
return result;
});
检查here
还要注意以下几点:
关于javascript - 从装饰器设置 View 名称-Angular Ui Router,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33112912/