正如@cshion 所说,您可以抓住$stateNotFound 并转到另一个状态
或者你想要的东西。
app.run(['$rootScope', '$state', function ($rootScope, $state) {
$rootScope.$on("$stateNotFound", function (event, unfoundState, fromState, fromParams) {
$state.go('my404state');
});
}]);
这只能通过调用$state.go('missingstate'); 起作用但是如果用户输入一个虚假的url 则不起作用。所以更适合测试/调试目的。
另一方面,您可以使用 $urlRouterProvider.otherwise 重定向用户
app.config( ['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.when('/', [$state, function($state) { $state.go('home') }])
.otherwise('/notfound');
}
]);
并创建一个特定的状态来显示 404 not found。
编辑:基于 cmets。
另一种选择是使用$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.