2015-09-15 116 views
0

我想重定向到另一个状态上stateChangeStartevent.preventDefault$state.go()不能渲染视图。如果我评论他们两人,它会开始工作。这里是plunkerUI路由器event.preventDefault不会呈现UI视图

var example = angular.module("example", ['ui.router']); 

example.config(function ($stateProvider, $urlRouterProvider) { 
    $stateProvider 
     .state("root", { 
      url: "/", 
      abstract: true, 
      template: '<ui-view>' 
     }) 
     .state("root.second", { 
      abstract: true, 
      template: '<ui-view>', 
     }) 
     .state("root.second.a", { 
      url: "a", 
      template: "second a template", 
     }) 
     .state("root.first", { 
      abstract: true, 
      template: '<ui-view>' 
     }) 
     .state("root.first.b", { 
      url: "b", 
      template: "first a template" 
     }); 

    $urlRouterProvider.otherwise("/b"); 
}); 


example.run(function ($rootScope, $state) { 
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { 
     event.preventDefault(); 
     $state.go("root.second.a", {}, {notify: false}); 
    }); 

}); 

回答

1

设置notifyprevents the view directive from doing it's job。而不是使用notify: false,我假设您正在做的以避免$stateChangeStart函数,您可以有条件地调用$state.go()

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { 
    if (toState.name !== 'root.second.a') { 
    event.preventDefault(); 
    $state.go('root.second.a'); 
    } 
}); 

Plunker:http://plnkr.co/edit/tJPxXGir5YSSPG5jGodn?p=preview

+0

如果我想重定向所有的请求?那又怎么样?另请参阅https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-create-rules-to-prevent-access-to-a-state – norbertpy

+0

如果没有通知:假',我会以无限循环结束。 – norbertpy

+0

我提供的代码和plunker链接显示它适用于所有请求,并且不会以无限循环结束。如果目标状态是'root.second.a',则不会调用条件代码。也许你应该修改你的问题,提供关于你的用例的更多细节,因为这看起来并不理想。 –