我一直在重构我的网站以使用ui.router 1. *和组件路由。
我想出了一个解决方案,见下文。但是,我想知道这是否是正确的方法?将$ transition注入到我的主组件中我并不高兴,但我不确定如何才能实现动态菜单。
我考虑在app.run中定义这些钩子,但不确定如何访问,或者即使获得master.menuComponents和alter也是一种好习惯。
这样做是否会导致跌倒?
的index.html
<!docttype html>
<html>
<head>
<!--script stuff-->
</head>
<ui-view></ui-view>
</html>
app.component('master', {
bindings: {menuComponents: '<'},
template: '<body>' +
'<nav class="navbar navbar-inverse navbar-fixed-top" role="naviation">' +
'<div class="navbar-header">' +
'<a class="navbar-brand" ui-sref="#">My Dynamic Site</a>' +
'<ul class="nav navbar-nav">' +
'<li ng-repeat="menu in $ctrl.menuComponents">' +
'<a ui-sref="{{menu.state}}" ui-sref-active="active">{{menu.name}}</a>' +
'</li>' +
'</ul>' +
'</div>' +
'<ul class="nav navbar-nav">' +
'</ul>' +
'<ul class="nav navbar-nav pull-right">' +
'<li><a ui-sref="master.logout"><strong>logout</strong></a></li>' +
'</ul>' +
'</nav>' +
'<ui-view></ui-view>' +
'</body>',
controller: function(_, $transitions){
var vm = this;
$transitions.onExit({from: 'master.login'}, function(trans){
//get new menu's and states based on credentials
var $stateRegistry = trans.router.stateRegistry;
$stateRegistry.register({name:'master.dynamic1', url:'/dynamic1', template: '<h1>I Am Dynamic</h1>'});
vm.menuComponents.push({name:'dynamic1', state: 'master.dynamic1'});
});
$transitions.onEnter({to: 'master.logout'}, function(trans){
var $stateRegistry = trans.router.stateRegistry;
$stateRegistry.deregister('master.dynamic1');
_.remove(vm.menuComponents, {name:'dynamic1'});
});
}
});
$stateProvider
.state('master', {
url: '/master',
abstract: true,
component: 'master',
resolve: {
menuComponents : function(){ //would probably inject a menuService to return this
return [{name:'login', state: 'master.login'}];
}
}
}).state('master.login', {
url: '/login',
component: 'login'
}).state('master.logout', {
url: '/logout',
component: 'logout'
});
$urlRouterProvider.when('/', '/master/login')
.otherwise('/master/login');
前进并设置一个mongodb,其中包含我可以通过服务加载到ui.router中的菜单文档。一切似乎都很好,除了无法添加组件的状态。我是否会为此工作而懒得加载?
答案 0 :(得分:0)
看起来像git ui-router / sample-app-ng2可能提供一个很好的起点。