有没有更好的方法使用ui-router重定向状态?

时间:2015-04-02 20:07:20

标签: angular-ui-router

有没有更好的方法在不使用$ urlRouterProvider的情况下重定向状态?我想在经过base.home状态后重定向到其他地方。

    $stateProvider
        .state('base', {
            url: '/base',
            abstract: true,
            views: {
                "mainbase": {
                    templateUrl: 'ng/apps/base/views/header.html',
                    controller: 'HeaderCtrl'
                }
            },
        })
        .state('base.home', {
            url: '',
            views: {
                "baseHeaderView": {
                    template: 'base home, you should not be here',
                    controller: function($state) {
                        // Can this be accomplished better?
                        $state.go('base.elsewhere');
                    }   
                }
            }
        })
        .state('base.elsewhere',{
          url: '/elsewhere'
          //I want to redirect to here after going through the base.home state
        });

1 个答案:

答案 0 :(得分:0)

使用属性标记重定向状态,然后为$stateChangeStart添加全局侦听器并有条件地取代转换。

这会重定向以取代原始转换,因此“base.home”甚至不会暂时激活。如果你

 app.run($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function(evt, toState, params) {
      if (toState.redirectTo) {
        evt.preventDefault();
        $state.go(toState.redirectTo, params);
      }
    });
  }

  app.config(function($stateProvider) {
        $stateProvider.state('base', {
            url: '/base',
            abstract: true,
            views: {
                "mainbase": {
                    templateUrl: 'ng/apps/base/views/header.html',
                    controller: 'HeaderCtrl'
                }
            },
        })
        .state('base.home', {
            url: '',
            views: {
                "baseHeaderView": {
                    template: 'base home, you should not be here',
                    controller: function($state) {
                        // Can this be accomplished better?
                        $state.go('base.elsewhere');
                    }   
                }
            },
            redirectTo: 'base.elsewhere'
        })
        .state('base.elsewhere',{
          url: '/elsewhere'
          //I want to redirect to here after going through the base.home state
        });
  });