您不能仅使用$stateProvider
。
您需要注入$urlRouterProvider
并创建类似以下代码:
$urlRouterProvider.otherwise('/otherwise');
需要像平常一样在状态上定义 /otherwise
URL:
$stateProvider
.state("otherwise", { url : '/otherwise'...})
请查看此链接,在此处ksperling解释了
$stateProvider
。如果你只想显示一个模板而不是重定向,那么这样做会更简单。我更喜欢 @juan-hernandez 的答案。 - Dennis Hackethalotherwise
(在本例中为'/otherwise'
)的值必须与状态名称(.state
的第一个参数)或url
选项的值匹配吗? - d512$stateProvider
和catch all syntax ("*path"
)来实现。您只需要在列表底部添加一个状态配置,如下所示:$stateProvider.state("otherwise", {
url: "*path",
templateUrl: "views/error-not-found.html"
});
$urlRouterProvider.otherwise(...)
不同的是,这个选项的好处是你不需要强制进行位置更改。您还可以手动将$state注入到otherwise函数中,然后导航到非URL状态。这样做的好处是浏览器不会更改地址栏,这有助于处理返回到以前页面的操作。
$urlRouterProvider.otherwise(function ($injector, $location) {
var $state = $injector.get('$state');
$state.go('defaultLayout.error', {
title: "Page not found",
message: 'Could not find a state associated with url "'+$location.$$url+'"'
});
});
我只是想就已经提供的好答案发表意见。最新版本的@uirouter/angularjs
标记类UrlRouterProvider
为废弃。他们现��推荐使用UrlService
。您可以通过以下修改实现相同的结果:
$urlService.rules.otherwise('/defaultState');
附加方法:https://ui-router.github.io/ng1/docs/1.0.16/interfaces/url.urlrulesapi.html
好的,当你意识到你提出的问题已经在示例代码的第一行中得到了回答时,会有一些傻眼的时刻!只需查看示例代码即可。
angular.module('sample', ['ui.compat'])
.config(
[ '$stateProvider', '$routeProvider', '$urlRouterProvider',
function ($stateProvider, $routeProvider, $urlRouterProvider) {
$urlRouterProvider
.when('/c?id', '/contacts/:id')
.otherwise('/'); // <-- This is what I was looking for !
....
已接受的答案中提到了angular-route
,但是询问的是ui-router
。已接受的答案使用"单体"$routeProvider
,需要ngRoute
模块(而ui-router
需要ui.router
模块)。
最高评分的答案使用$stateProvider
,并且类似于.state("otherwise", { url : '/otherwise'... })
,
但我在它链接的文档中找不到“otherwise”的任何提及。然而,我看到$stateProvider
在这个答案中被提到:
这就是我的答案可能会帮到你的地方。对我来说,只需要像这样使用你不能仅使用
$stateProvider
。你需要注入$urlRouterProvider
$urlRouterProvider
就足够了: my_module
.config([
, '$urlRouterProvider'
, function(
, $urlRouterProvider){
//When the url is empty; i.e. what I consider to be "the default"
//Then send the user to whatever state is served at the URL '/starting'
//(It could say '/default' or any other path you want)
$urlRouterProvider
.when('', '/starting');
//...
}]);
我的建议与 ui-router
文档 (这个特定版本) 一致,其中包括类似使用 .when(...)
方法的方式(函数的第一个调用):
app.config(function($urlRouterProvider){
// when there is an empty route, redirect to /index
$urlRouterProvider.when('', '/index');
// You can also use regex for the match parameter
$urlRouterProvider.when(/aspx/i, '/index');
})
$stateProvider.otherwise
,所以这会帮助我) - Kevin Meredith