---
title: "AngularUI Router 概要"
author: "rensanning"
date: "2014-10-29T09:32:39Z"
tags: []
categories: ["Web前端"]
slug: "angularui-router"
draft: false
lastmod: "2015-04-21T15:46:10Z"
id: 2149056
url: "https://rensanning.iteye.com/blog/2149056"
---

通过AngularJS来创建SPA（single page application），要想让页面导航看起来跟一般Web页面一样的话，路由相当重要。AngularUI Router是AngularUI 团队开发的一个AngularJS路由模块，相比AngularJS的标准路由ngRoute，它更灵活，基于state而不是URL在一个页面中加载多个View并保持View的层次，Nested States & Views以及Multiple & Named Views。UI-Router被认为是AngularUI为开发者提供的最实用的一个模块。 和ngRoute相比： \[list]\[\*]$route -&gt; $state \[\*]$routeParams -&gt; $stateParams \[\*]$routeProvider -&gt; $stateProvider \[\*]

-&gt;

\[/list] \[b]（1）设置路由\[/b] 在.config()方法中使用$stateProvider（不是$routeProvider）来配置应用或者模块的state： \[code="js"]$stateProvider.state('state名', {设置信息});\[/code] 但是默认otherwise需要使用$urlRouterProvider来设置 \[code="js"]$urlRouterProvider.otherwise('/tab/home');\[/code] 设置whenPath（可用正则），当匹配是直接跳转到toPath \[code="js"]$urlRouterProvider.when(whenPath, toPath);\[/code] 自定义URL捕获处理，handler方法有一个参数$location返回一个path \[code="js"]$urlRouterProvider.rule(handler);\[/code] 例如： \[code="js"]$stateProvider .state("emp",{ url:"/emp" ,templateUrl:"list.html" ,controller:"ListCtrl" }) .state("emp.detail",{ url:"/:empID" ,templateUrl:"emp.html" ,controller:"EmpCtrl" });\[/code] ngRoute的设置方法： \[code="js"]$routeProvider.when('url', {设置信息});\[/code] 例如： \[code="js"]$routeProvider .when("/emp",{ templateUrl:"list.html" ,controller:"ListCtrl" }) .when("/emp/:empID"){ templateUrl:"emp.html" ,controller:"EmpCtrl" };\[/code] \[b]（2）层次化\[/b] state可以嵌套，state名必须唯一，通过state名中的点来划分Parent/child层次。 格式为：父View.子View 比如：items.detail是items的子View。 \[code="js"]$stateProvider .state("items", { abstract: true, url: "/items" templateUrl: "items.html" // 必须包含 }) .state("items.detail", { url: "/detail", // URL就是"/items/detail" templateUrl: "items-detail.html" }) .state("items.info", { url: "/info", // URL就是"/items/info" templateUrl: "items-info.html" });\[/code] \[b]（3）设置信息\[/b] url：默认相对路径（以^开头的是绝对路径） views：每个子视图可以包含自己的模板、控制器和预载入数据。 abstract：设置为true时，只能被继承不能直接切换到此state template、templateUrl、templateProvider：HTML字符串或者返回HTML字符串的函数、HTML模板的路径或者返回HTML模板路径的函数 controller、controllerProvider：可以是一个控制器函数或者已经被注册的控制器名称，controllerProvider是一个注入函数返回控制器函数或控制器名称 resolve：在路由到达前预载入一系列依赖或者数据，然后注入到控制器中。 data：数据不会被注入到控制器中，用途是从父状态传递数据到子状态。 onEnter/onExit：进入或者离开当前状态的视图时会调用这两个函数 URL使用举例： url: '/inbox' url: '/inbox/:inboxId' url: '/inbox/{inboxId}' url: '/inbox/{inboxId:\[0-9a-fA-F]{6}}' url: '/inbox/{inboxId:.\*}' url: '/inbox?sort' url: '/inbox/:inboxId/messages/{sorted}?from&to' url: '/party/:partyID/:partyLocation' url: '/product/info/favorite?pid&jancode&showAddFavorite&fromPg' \[b]（4）指定View名\[/b] \[code="html"]

\[/code] \[code="js"].state("emp.detail"),{ url:"/:empID" ,views:{ view1:{ templateUrl:"view1.html" ,controller:"View1Ctrl" } ,view2:{ templateUrl:"view1.html" ,controller:"View1Ctrl" } } }\[/code] 初始View \[code="js"].state("emp.detail"),{ url:"/:empID" ,views:{ "":{ templateUrl:"emp.html" ,controller:"EmpCtrl" } } }\[/code] view@state \[code="js"].state("emp.detail.picture"),{ url:"/all" ,views:{ "@emp":{ templateUrl:"picture.html" ,controller:"PictureCtrl" } } }\[/code] \[b]（5）页面跳转\[/b] 链接点击后跳转到指定state \[code="html"][Go](#/emp/hoge/1234) [Go]()\[/code] \[code="js"]$state.go('state名' \[, 参数] \[, 可选项]);\[/code] 参数在下一个控制器中通过$stateParams接收 可选项： location：true(更新地址栏)、false(不更新地址栏)、replace(更新地址栏同时更新history记录) inherit：true（继承当前URL的参数）、false relative：跳转原来的state对象 notify：true（激发$stateChangeStart和$stateChangeSuccess）、false reload：重新加载 \[code="js"]$state.reload(); $state.includes(stateName \[, params]); $state.is(stateOrName \[, params]); $state.href(stateOrName \[, params] \[, options]); $state.get(\[stateName]); $state.current\[/code] \[b]（6）事件\[/b] state事件 \[list]\[\*]$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ ... }) \[\*]$rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){ ... }) \[\*]$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ ... }) \[\*]$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){ ... })\[/list] view事件 View被加载但是DOM树构建之前时： \[code="js"]$scope.$on('$viewContentLoading', function(event, viewConfig){ ... });\[/code] View被加载而且DOM树构建完成时： \[code="js"]$scope.$on('$viewContentLoaded', function(event){ ... });\[/code] 参考： https://github.com/angular-ui/ui-router https://docs.angularjs.org/api/ngRoute http://angular-ui.github.io/ui-router/sample/ http://scotch.io/tutorials/javascript/angular-routing-using-ui-router http://blog.eisneim.com/articles/dive\_deep\_into\_ui-router.html