angularjs – 如果特定stateParam为空,如何重定向到状态
我不知道如果我做的方式是正确的,任何建议将不胜感激。
我有一个餐厅选择,用户可以从中选择餐厅。然后所有其他子状态加载特定于所选择的餐馆的内容。但我需要在默认情况下选择一个子状态,包括一个餐厅,根据用户最近的位置或cookie数据(如果他们以前选择了一个)。但是,我不知道如何我可以重定向到一个孩子的状态,默认情况下,不知道餐厅的id已经? 我的代码的混蛋版下面说明。 app.config(function ($stateProvider,$urlRouterProvider) { $urlRouterProvider.otherwise("/restaurant/[some id based on cookie info]/our-food"); // if no id is set,then I want to get it from a cookie,but then how do i do the redirect? $stateProvider .state('restaurant',{ url: '/restaurant/:restaurantId',template: "<ui-view/>",controller: function($state,$stateParams,Data,RestaurantService,$cookieStore) { if(typeof $stateParams.restaurantId !== 'undefined') { // get the restaurantID from the cookie } } }) .state('restaurant.our-food',{ url: '/our-food',templateUrl: function($stateParams) { return 'templates/food-food.html?restaurantId=' + $stateParams.restaurantId; },controller: 'SubNavCtrl' }) .state('restaurant.glutenfree-vegetarian',{ url: '/glutenfree-vegetarian',templateUrl: function($stateParams) { return 'templates/food-vegetarian.html?restaurantId=' + $stateParams.restaurantId; },controller: 'SubNavCtrl' }) 下面的图片说明了前端发生了什么:
我会创建一个事件,每当你打开该特定状态时触发。
查看他们的文档:https://github.com/angular-ui/ui-router/wiki#onenter-and-onexit-callbacks 所以我的猜测是这样的东西 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,$cookieStore) { if(typeof $stateParams.restaurantId !== 'undefined') { sate.go('restaurant',$cookieStore['restaurant']) } }] 这可能是发展方面最快的解决方案,但我相信使用事件更干净,并使更容易理解的代码。 注意:我没有实际运行任何这样的代码,所以它可能不工作,它只是伪代码,给你一个想法,去哪里。让我知道如果你遇到问题。 编辑:Acutally我不知道stateParams是否传递到控制器。您可能必须使用resolve来访问它们。 编辑:在onEnter回调或控制器访问stateParams,我相信你必须使用解决方案: resolve: { checkParam: ['$state',$cookieStore) { //logic in here,what it returns can be accessed in callback or controller. }] 请参阅ui-router doc解决更多的例子/更好的解释 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |