조건부보기를 수행하는 Angular UI 라우터
-
21-12-2019 - |
문제
이 질문에 유사한 질문을하고 있습니다 : UI 라우터 조건부 UI views? 그러나 내 상황은 조금 더 복잡하고 있으며, 내가 제공된 답변을 얻는 것처럼 보일 수는 없습니다.
기본적으로 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 서비스에서 실제 엔티티를 가져 오기 위해 해결을 설정했습니다. 모든 일은 실제로 유형에 따라 전환 할 때까지 일하는 것 같습니다.
ID가 null이기 때문에 재사용 해결을 제외하고 getEntity가 실패한 경우 전환이 작동하는 것 같습니다.
은 ID를 전환 호출로 보내려고했지만 여전히 두 번째 해결을 시도합니다. 즉, 엔티티가 REST 서비스에서 두 번 가져온 것을 의미합니다.
해결책
TemplyURL 기능이뿐만 아니라 유형을 확인하고 다른 것을 반환 할 수 있습니다.상태 구성의 일부가 아닌보기에서 컨트롤러를보고 정의하십시오.TemplateRubider를 사용해야 할 수있는 매개 변수를 삽입 할 수 없습니다.
$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. 해결의 결과에 따라 첫 번째 또는 두 번째로
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