Angular UI-Router完成条件视图
-
21-12-2019 - |
题
我问这个问题类似的问题: ui路由器条件UI视图?,但我的情况更复杂,我似乎无法获得工作的答案。
基本上,我有一个可以呈现两种非常不同的方式的URL,具体取决于URL指向的实体类型。
$stateProvider
.state('home', {
url : '/{id}',
resolve: {
entity: function($stateParams, RestService) {
return RestService.getEntity($stateParams.id);
}
},
template: 'Home Template <ui-view></ui-view>',
onEnter: function($state, entity) {
if (entity.Type == 'first') {
$state.transitionTo('home.first');
} else {
$state.transitionTo('home.second');
}
}
})
.state('home.first', {
url: '',
templateUrl: 'first.html',
controller: 'FirstController'
})
.state('home.second', {
url: '',
templateUrl: 'second.html',
controller: 'SecondController'
});
.
我设置了一个解析,从RESTful Service获取实际实体。 每件事似乎都在努力,直到我基于类型到达过渡到过渡。
转换似乎工作,除了解析重新触发和全职失败,因为ID为null。
解决方案
templateUrl 可以是一个功能,所以您检查类型并返回不同查看并在视图中定义控制器而不是作为状态配置的一部分。您无法将参数注入TemplateURL,因此您可能必须使用TemplateProvider。
$stateProvider.state('home', {
templateProvider: ['$stateParams', 'restService' , function ($stateParams, restService) {
restService.getEntity($stateParams.id).then(function(entity) {
if (entity.Type == 'first') {
return '<div ng-include="first.html"></div>;
} else {
return '<div ng-include="second.html"></div>';
}
});
}]
})
. 其他提示
您还可以执行以下操作:
$stateProvider
.state('home', {
url : '/{id}',
resolve: {
entity: function($stateParams, RestService) {
return RestService.getEntity($stateParams.id);
}
},
template: 'Home Template <ui-view></ui-view>',
onEnter: function($state, entity) {
if (entity.Type == 'first') {
$timeout(function() {
$state.go('home.first');
}, 0);
} else {
$timeout(function() {
$state.go('home.second');
}, 0);
}
}
})
.state('home.first', {
url: '',
templateUrl: 'first.html',
controller: 'FirstController'
})
.state('home.second', {
url: '',
templateUrl: 'second.html',
controller: 'SecondController'
});
. 我最终使家庭控制器成为第一和第二,而不是父的兄弟,然后将家庭控制器执行$ state.go至第一或第二,具体取决于解决的结果。
在UI-Route中使用验证代码
$stateProvider.state('dashboard.home', {
url: '/dashboard',
controller: 'MainCtrl',
// templateUrl: $rootScope.active_admin_template,
templateProvider: ['$stateParams', '$templateRequest','$rootScope', function ($stateParams, templateRequest,$rootScope) {
var templateUrl ='';
if ($rootScope.current_user.role == 'MANAGER'){
templateUrl ='views/manager_portal/dashboard.html';
}else{
templateUrl ='views/dashboard/home.html';
}
return templateRequest(templateUrl);
}]
});
. 不隶属于 StackOverflow