4、Angular-Ui Router URL路由(完结篇)

2141人阅读 评论(0) 收藏 举报

Most states in your application will probably have a url associated with them. URL Routing was not an afterthought to the state mechanics, but was figured into the design from the beginning (all while keeping states separate from url routing)
应用程序中的大多数状态可能会有一个与之关联的 url。url 路由不是对状态机制的事后考虑, 而是从一开始就被设计到了设计中 (所有的状态都保持与 url 路由分开)

Here's how you set a basic url.

    .state('contacts', {
        url: "/contacts",
        templateUrl: 'contacts.html'

Now when the user accesses index.html/contacts then the 'contacts' state would become active and the main ui-view will be populated with the 'contacts.html' partial. Alternatively, if the user were to transition to the 'contacts' state via transitionTo('contacts') then the url would be updated to index.html/contacts
当用户访问 index.html/contacts时。然后,“contacts”状态将变为活动,ui-view将被“contacts.html”填充。或者,如果用户通过transitionTo("contacts")切换到“contacts”状态,那么url将被更新为index.html/contacts

URL Parameters

Basic Parameters

Often, URLs have dynamic parts to them which are called parameters. There are several options for specifying parameters. A basic parameter looks like this:

    .state('contacts.detail', {
        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"});

Alternatively you can also use curly brackets:

// identical to previous example
url: "/contacts/{contactId}" 


  • '/hello/' - Matches only if the path is exactly '/hello/'. There is no special treatment for trailing slashes, and patterns have to match the entire path, not just a prefix.
  • '/user/:id' - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
    '/user/:id' - 匹配 '/user/bob' 或 '/user/1234!!!' 或者是 '/user/' 但不是 '/user' 或 '/user/bob/details'. 第二个路径段将被捕获为参数'id'。
  • '/user/{id}' - Same as the previous example, but using curly brace syntax.
    '/user/{id}' - 与前面的示例相同,但使用的是花括号语法。
  • '/user/{id:int}' - The param is interpreted as Integer.
    '/user/{id:int}' - id参数被解释为整数。


  • Parameter names may contain only word characters (latin letters, digits, and underscore) and must be unique within the pattern (across both path and search parameters).
    参数名称只能包含字母、数字和下划线, 并且在模式中必须是唯一的 (在路径和搜索参数中)。

Using Parameters in Links

To create a link that passes parameters, use the state name like a function and pass it an object with parameter names as keys. The proper href will be generated.

For example, using the above state which specified a contactId parameter, create a link like so:
例如, 使用指定了 contactId 参数的上述状态, 创建如下链接:

<a ui-sref="contacts.detail({contactId: id})">View Contact</a>

The value for id can be anything in scope.

Regex Parameters

A bonus to using curly brackets is the ability to set a Regular Expression rule for the parameter:

// will only match a contactId of one to eight number characters
url: "/contacts/{contactId:[0-9]{1,8}}"


  • '/user/{id:[^/]*}' - Same as '/user/{id}' from the previous example.
    '/user/{id:[^/]*}' - 与前一个示例中的“/user/id”相同。
  • '/user/{id:[0-9a-fA-F]{1,8}}' - Similar to the previous example, but only matches if the id parameter consists of 1 to 8 hex digits.
    '/user/{id:[0-9a-fA-F]{1,8}}' - 与前面的示例类似,但是只有当id参数包含1到8十六进制数字时才匹配。
  • '/files/{path:.*}' - Matches any URL starting with '/files/' and captures the rest of the path into the parameter 'path'.
    '/files/{path:.*}' - 匹配任何以'/files/'开头的URL,并将其余路径捕获到参数“path”中。
  • '/files/*path' - Ditto. Special syntax for catch all.


  • Don't put capturing parentheses into your regex patterns, the UrlMatcher in ui-router adds those itself around the entire regex. You're effectively introducing a second capture group for the same parameter, which trips up the numbering in the child URL. You can use non-capturing groups though, i.e. (?:...) is fine.
  • Regular expression can't include forward slashes as that's route segment delimiter
  • Route parameters with regular expressions can't be optional or greedy

Query Parameters

You can also specify parameters as query parameters, following a '?':
还可以将参数指定为查询参数, 即'?':

url: "/contacts?myParam"
// will match to url of "/contacts?myParam=value"

If you need to have more than one, separate them with an '&':

url: "/contacts?myParam1&myParam2"
// will match to url of "/contacts?myParam1=value1&myParam2=wowcool"

Using Parameters without Specifying Them in State URLs

You still can specify what parameters to receive even though the parameters don't appear in the url. You need to add a new field params in the state and create links as specified in Using Parameters in Links

For example, you have the state.

.state('contacts', {
        url: "/contacts",
        params: {
            param1: null
        templateUrl: 'contacts.html'

The link you create is

<a ui-sref="contacts({param1: value1})">View Contacts</a>

Or you can pass them to $state.go() too.

$state.go('contacts', {param1: value1})

URL Routing for Nested States

Appended Routes (default)

When using url routing together with nested states the default behavior is for child states to append their url to the urls of each of its parent states.

  .state('contacts', {
     url: '/contacts',
  .state('contacts.list', {
     url: '/list',

So the routes would become:

  • 'contacts' state matches "/contacts"
  • 'contacts.list' state matches "/contacts/list". The urls were combined.

Absolute Routes (^)

If you want to have absolute url matching, then you need to prefix your url string with a special symbol '^'.
如果你想要有绝对的url匹配,那么你需要在你的url字符串前面加上一个特殊的符号 '^'

  .state('contacts', {
     url: '/contacts',
  .state('contacts.list', {
     url: '^/list',

So the routes would become:

  • 'contacts' state matches "/contacts"
    'contacts' 状态匹配 "/contacts"
  • 'contacts.list' state matches "/list". The urls were not combined because ^ was used.
    url'contacts.list' 状态匹配"/list",现在url没有被组合在一起,因为使用了'^'符号。

$stateParams Service

As you saw previously the $stateParams service is an object that will have one key per url parameter. The $stateParams is a perfect way to provide your controllers or other services with the individual parts of the navigated url.

Note: $stateParams service must be specified as a state controller, and it will be scoped so only the relevant parameters defined in that state are available on the service object.

// If you had a url on your state of:
url: '/users/:id/details/{type}/{repeat:[0-9]+}?from&to'

// Then you navigated your browser to:

// Your $stateParams object would be
{ id:'123', type:'', repeat:'0' }

// Then you navigated your browser to:

// Your $stateParams object would be
{ id:'123', type:'default', repeat:'0', from:'there', to:'here' }

Important $stateParams Gotcha

In state controllers, the $stateParams object will only contain the params that were registered with that state. So you will not see params registered on other states, including ancestors.

$stateProvider.state('contacts.detail', {
   url: '/contacts/:contactId',   
   controller: function($stateParams){
      $stateParams.contactId  //*** Exists! ***//
}).state('contacts.detail.subitem', {
   url: '/item/:itemId', 
   controller: function($stateParams){
      $stateParams.contactId //*** Watch Out! DOESN'T EXIST!! ***//
      $stateParams.itemId //*** Exists! ***//  

Instead, use a resolve statement in the parent route.

$stateProvider.state('contacts.detail', {
   url: '/contacts/:contactId',   
   controller: function($stateParams){
      $stateParams.contactId  //*** Exists! ***//
      contactId: ['$stateParams', function($stateParams){
          return $stateParams.contactId;
}).state('contacts.detail.subitem', {
   url: '/item/:itemId', 
   controller: function($stateParams, contactId){
      contactId //*** Exists! ***//
      $stateParams.itemId //*** Exists! ***//  


$urlRouterProvider has the responsibility of watching $location. When $location changes it runs through a list of rules one by one until a match is found. $urlRouterProvider is used behind the scenes anytime you specify a url in a state configuration. All urls are compiled into a UrlMatcher object (see $urlMatcherFactory below).

There are several methods on $urlRouterProvider that make it useful to use directly in your module config.

when() for redirection


  • what String | RegExp | UrlMatcher 您想要重定向的源路径。
  • handler String | Function 您希望将用户重定向到的目标路径。

handler 作为字符串类型时

If handler is a string, it is treated as a redirect, and is interpolated according to the syntax of match (i.e. like String.replace() for RegExp, or like a UrlMatcher pattern otherwise).

    // 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 作为函数时

If the handler is a function, it is injectable. It gets invoked if $location matches. You have the option of inject the match object as $match


  • falsy to indicate that the rule didn't match after all, then $urlRouter will continue trying to find another one that matches. 
  • String, which is treated as a redirect and passed to $location.url()
  • nothing or any truthy value tells $urlRouter that the url was handled
    nothing 或任何 truthy值,意思告诉 $urlRouter 该 url 已被处理

Here's the actual code that we use to register state's that have urls behind the scenes.

$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
    if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
        $state.transitionTo(state, $match, false);

otherwise() for invalid routes


  • path String | Function The url path you want to redirect to or a function rule that returns the url path. The function version is passed two params: $injector and $location.
    path String | Function 您想要重定向的url路径,或者返回url路径的函数。函数版本有两个参数:$injector和$location。
    // if the path doesn't match any of the urls you configured
    // otherwise will take care of routing the user to the specified url

    // Example of using function rule as param
    $urlRouterProvider.otherwise(function($injector, $location){
        ... some advanced code...

rule() for custom url handling


  • handler Function A function that takes in the $injector and $location services as arguments. You are responsible for returning a valid path as a string.
    handler Function 一个函数,它接受$injector和$location服务作为参数。函数需要返回一条有效字符串路由。
app.config(function ($urlRouterProvider) {
   // Here's an example of how you might allow case insensitive urls
   // Note that this is an example, and you may also use 
   // $urlMatcherFactory.caseInsensitive(true); for a similar result.
   $urlRouterProvider.rule(function ($injector, $location) {
       //what this function returns will be set as the $location.url
        var path = $location.path(), normalized = path.toLowerCase();
        if (path != normalized) {
            //instead of returning a new url string, I'll just change the $location.path directly so I don't have to worry about constructing a new url string and so a new state change is not triggered
        // because we've returned nothing, no state change occurs

$urlMatcherFactory and UrlMatchers
$urlMatcherFactory 和 UrlMatchers

Defines the syntax for url patterns and parameter placeholders. This factory service is used behind the scenes by $urlRouterProvider to cache compiled UrlMatcher objects, instead of having to re-parse url patterns on every location change. Most users will not need to use $urlMatcherFactory directly, however it could be useful to craft a UrlMatcher object and pass it as the url to the state config.

Please refer to the comment documentation within the $urlMatcherFactory file to learn more.

var urlMatcher = $urlMatcherFactory.compile("/home/:id?param1");
$stateProvider.state('myState', {
    url: urlMatcher 




来自:http://blog.fens.me/series-angular/ URL的#号问题 使用AngularJS的朋友都应该了解,AngularJS框架定义了自己的前端路由控制器,通过不同URL实现单面(ng-app)对视图(ng-view)的部署刷新,并支持HTML5的历史记...
  • lxhjh
  • lxhjh
  • 2016-01-31 13:01
  • 2889

ANGULAR2 深入学习路由

基础 大多数带路由的应用都要在 index.html 的  标签下先添加一个  元素,来告诉路由器该如何合成导航用的 URL 。 如果 app 文件夹是该应用的根目录,那就把 href 的值设置为...
  • huangyezi
  • huangyezi
  • 2016-07-26 13:05
  • 11857

【ionic+angularjs】angularjs ui-router路由简介($urlRouter、$state、$stateProvider、ui-sref....)

原文出处:http://www.cnblogs.com/ys-ys/p/5052660.html?utm_source=tuicool&utm_medium=referral         之前有写过一篇关于Angular自带的路由...
  • MCpang
  • MCpang
  • 2017-02-14 16:45
  • 10277

angular 使用 ui-router 设计网页

  • fansongy
  • fansongy
  • 2015-03-09 23:06
  • 49932

angular ui-router 路由默认跳转语句$urlRouterProvider.otherwise(‘路径');与<a>共用时存在的问题

当angular路由设置默认跳转路径$urlRouterProvider.otherwise(‘default'),并且页面存在标签并且标签设置属性href="###"即时,每次点击标签都会跳转到‘’default'页面。 解决该问题的方法就是去掉l标签的属性h...
  • bem_zj
  • bem_zj
  • 2017-05-21 22:16
  • 3579

Angular 关于获取Matrix URL 和 普通URL 查询字符串问题

Angular 文档上关于怎么来获取这两种URL规范的querystring并没有给出详细的解释。ActivatedRoute文档:interface ActivatedRoute { snapshot: ActivatedRouteSnapshot url: Observable<...
  • HaoDaWang
  • HaoDaWang
  • 2017-08-11 22:33
  • 487

angular router ui 路由模块(父子)层级说明

路由配置页面 /***************** 英雄榜 ************************/ //英雄榜模板 .state('heroTopList', { url: '/heroTopList', abstract:true, templat...
  • hbiao68
  • hbiao68
  • 2016-09-07 18:08
  • 215


转载请注明出处:王亟亟的大牛之路不知不觉Router部分的内容已经写到第四篇了,这一篇会再点一点histroy以及实现一个提交表单的例子还是老规矩,先安利一下:https://github.com/ddwhan0123/Useful-Open-Source-Android (安卓的路由跳转部分拆了出...
  • ddwhan0123
  • ddwhan0123
  • 2017-02-27 16:48
  • 3252

angularjs 关于ui-router分层使用

最近感觉有很多学angular 的童鞋在路由问题中还不清楚怎么使用。其实我之前也是一直晕晕的不懂怎么用,现在要好得多了。在这里就记录下ui-router使用。 就已目前做的这个项目来介绍下怎么使用吧。Note:最好是按照层次规则来设置路由名,好处是容易看懂,也便于管理。 我这里是以总state到...
  • u012138137
  • u012138137
  • 2016-03-04 17:04
  • 1286

angular ui.router 路由传参数

angular已经用了一段时间了,最近在做路由跳转的时候对url所带的参数问题进行了点研究,做一下笔记哦。 首先,angular本身就有获取url参数的服务,$location,比如 href="abc.htnl?a=1&b=2",可以利用$location.searc...
  • jinuxm
  • jinuxm
  • 2016-11-10 10:57
  • 2011
    • 访问:327007次
    • 积分:3313
    • 等级:
    • 排名:第12199名
    • 原创:86篇
    • 转载:10篇
    • 译文:5篇
    • 评论:159条