UI-Router:在缺失状态下更改模板

时间:2014-09-08 21:13:29

标签: angularjs angular-ui-router

当用户访问缺失状态时,是否可以“设置”视图?如果用户试图访问不存在的页面而不是重定向用户,我希望404处理程序只有一些通知。

Github's 404类似的东西。

2 个答案:

答案 0 :(得分:4)

正如@cshion所说,你可以抓住$stateNotFound并进入另一个州 或者你想要的东西。

app.run(['$rootScope', '$state', function ($rootScope, $state) {
  $rootScope.$on("$stateNotFound", function (event, unfoundState, fromState, fromParams) {
        $state.go('my404state');
  });
}]);

这只能通过调用$state.go('missingstate'); 来起作用,但如果用户输入的假网址不起作用。那么更适合测试/调试目的。

另一方面,您可以使用$urlRouterProvider.otherwise

重定向用户
app.config( ['$stateProvider', '$urlRouterProvider',
   function ($stateProvider,   $urlRouterProvider) {
       $urlRouterProvider
           .when('/', [$state, function($state) { $state.go('home') }])
           .otherwise('/notfound');
    }
]);

创建一个特定的状态以显示404未找到。

编辑:基于评论。

另一种选择是使用$urlRouterProvider.rule进行自定义网址处理

app.config(['$urlRouteProvider','MyAuthService', function ($urlRouterProvider) {

   $urlRouterProvider
         .when('/', [$state, function($state) { $state.go('home') }])
         .rule(function ($injector, $location) {
               if (MyAuthService.isAuthenticated()) {
                   return "/user/mainpage";
               }
               return $location.path();
          })
         .otherwise('/notfound');
}])

Note that otherwise wraps a rule that returns the same url that receive.

答案 1 :(得分:1)

您可以在app.run函数中查看状态更改事件。 像这样......

app.run(function ($rootScope, $state) {
  $rootScope.$on("$stateNotFound", function (event, unfoundState, fromState, fromParams) {
        //manage state not found
  });
});

来源:https://github.com/angular-ui/ui-router/wiki

相关问题