Directing the user to a child state when they are transitioning to its parent state using UI-Router

前端 未结 9 705
忘掉有多难
忘掉有多难 2020-11-30 19:06

Consider the following:

.state(\'manager.staffList\', {url:\'^/staff?alpha\', templateUrl: \'views/staff.list.html\', data:{activeMenu: \'staff\'}, controlle         


        
9条回答
  •  执念已碎
    2020-11-30 19:42

    I ran into the same issue and found this solution to work:

    https://github.com/angular-ui/ui-router/issues/948#issuecomment-75342784

    This is quoted from @christopherthielen on github

    "For now, don't declare your state abstract, and use this recipe:"

     app.run($rootScope, $state) {
        $rootScope.$on('$stateChangeStart', function(evt, to, params) {
          if (to.redirectTo) {
            evt.preventDefault();
            $state.go(to.redirectTo, params)
          }
        });
      }
    
      $stateProvider.state('parent' , {
          url: "/parent",
          templateUrl: "parent.html",
          redirectTo: 'parent.child'
      });
    
      $stateProvider.state('parent.child' , {
          url: "/child",
          templateUrl: "child.html"
      });
    

    Here is breakdown of how the process works:

    1. User navigates to state “parent”
    2. “$stateChangeStart” event gets fired
    3. Listener for “$stateChangeStart” catches event and passes “toState” (which is “parent”) and “event" to the handler function
    4. Handler function checks if “redirectTo” is set on “toState”.
    5. If “redirectTo” IS NOT set, nothing happening and the user continues on to the “toState” state.
    6. If “redirectTo" IS set, the event is canceled (event.preventDefault) and $state.go(toState.redirectTo) sends them to the state specified in “redirectTo” (which is “parent.child”).
    7. The “$stateChangeStart” event gets fired again, but this time “toState” == “parent.child” and the “redirectTo” option is not set, so it continues to “toState”.

提交回复
热议问题