$stateProvider .state('contacts.detail', { // 这里设置了url参数 url: "/contacts/:contactId", templateUrl: 'contacts.detail.html', controller: function ($stateParams) { // If we got here from a url of /contacts/42 expect($stateParams).toBe({contactId: 42}); } })
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'); })
handler 作为 Function 如果handler是一个函数,这个函数是注入一些服务的。如果$location匹配成功,函数将被调用。你可以选择性注入$match。
函数可以返回:
falsy 表明规则不匹配,$urlRouter将试图寻找另一个匹配
String 该字符串作为重定向地址并且作为参数传递给$location.url()
nothing或者任何为真的值,告诉$urlRouterurl 已经被处理
示例:
1 2 3 4 5
$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) { if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) { $state.transitionTo(state, $match, false); } }]);
otherwise() 无效路由
参数:
pathString | Function 你想重定向url路径或者一个函数返回url路径。函数可以包含$injector和$location两个参数。
1 2 3 4 5 6 7 8 9 10
app.config(function($urlRouterProvider){ // 在配置(状态配置和when()方法)中没有找到url的任何匹配 // otherwise will take care of routing the user to the specified url $urlRouterProvider.otherwise('/index');
// Example of using function rule as param $urlRouterProvider.otherwise(function($injector, $location){ ... some advanced code... }); })
app.config(function($urlRouterProvider){ // Here's an example of how you might allow case insensitive urls $urlRouterProvider.rule(function ($injector, $location) { var path = $location.path(), normalized = path.toLowerCase(); if (path != normalized) return normalized; }); })