我会创建一个事件,每次打开该特定状态时都会触发该事件。
查看他们的文档:https://github.com/angular-ui/ui-router/wiki#onenter-and-onexit-callbacks https://github.com/angular-ui/ui-router/wiki#onenter-and-onexit-callbacks
所以我的猜测是这样的
1.onEnter回调到餐厅状态(推荐)
$stateProvider.state("contacts", {
template: '<ui-view>',
resolve: ...,
controller: function($scope, title){
},
onEnter: function(){
if(paramNotSet){ $state.go(...)}
}
});
我自己从来没有使用过这样的事件,所以你可能需要下定决心做一些体操,但我相信这是最干净、最容易理解和最可维护的解决方案。
2 全局onStateChangeStart事件全局事件(尽管每次状态更改都会触发该事件)
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){ ... //check cookie, change state etc ...})
3 在控制器中或者,如果您想像开始一样使用控制器。
controller: ['$state', '$stateParams', 'Data', 'RestaurantService', '$cookieStore',
function($state, $stateParams, Data, RestaurantService, $cookieStore) {
if(typeof $stateParams.restaurantId !== 'undefined') {
sate.go('restaurant', $cookieStore['restaurant'])
}
}]
就开发而言,这可能是最快的解决方案,但我相信使用事件更干净,并且可以使代码更易于理解。
Note:我实际上没有运行过任何代码,所以它可能不起作用,它只是伪代码,可以让您了解该去哪里。如果您遇到问题,请告诉我。
EDIT:实际上我不确定状态参数是否传递到控制器。您可能必须使用解析才能访问它们。
EDIT:要访问 onEnter 回调或控制器中的 stateParams,我相信您必须使用解析:
resolve: {
checkParam: ['$state','$stateParams', '$cookieStore', function($state, $stateParams, $cookieStore) {
//logic in here, what it returns can be accessed in callback or controller.
}]
请参阅有关解决的 ui-router 文档以获取更多示例/更好的解释