UI-Router


SPA





SPA

(Single Page Application)


优势

(Advantages)

  • 减少向服务器请求网页的次数
  • 数据和表现分离(模块开发)
  • 充分利用客户端的能力(缓存页面等)
  • 易于测试

缺点

(Disadvantages)

  • 资源缓存过多可能导致内存泄漏
  • 浏览器必须支持JavaScript
  • 业务逻辑暴露在前端
  • SEO较困难

基本概念

  • ui-sref
  • ui-view
  • The Dot
  • $stateProvider
  • $urlRouterProvider
  • $stateParams
  • $state
  • @
  • Abstract States(抽象路由)
  • Events(路由事件)

Live Demo

ui-sref

相当于<a>标签的href
<li ng-repeat="contact in contacts">
   <a ui-sref="contacts.detail({ id: contact.id })"</a>
</li>
使用相对路径
 <a ui-sref='^'>Home</a>

ui-view

未命名
 <div ui-view></div>

The Dot®


$stateProvider    .state("home", { ... });    .state("contacts", { ... });
.state("contacts.detail", { ... });
.state("contacts.detail.edit", { ... });


在state中的'.'标明其父子关系。

所以 'contacts.detail'的父页面是 'contacts'.

Demo

命名
 <div ui-view="named"></div>
Demo

嵌套结构







$stateProvider

  $stateProvider.state('simple', {
    url: '/simple/:param',
    // or '/simple?param',
    // or '/simple/{param}',
    template: viewTemplate,
    // templateUrl: 'xxx.html',
    controller: 'viewCtrl' ,    // or 'viewCtrl as view'     // or function($scope,service)    resolve: {} // 作前期数据准备,完成后才会实例化controller,    data: {} // 提供自定义数据    params: {} // 设置默认参数    views: {      'viewname@statename' // 绝对视图概念      } // 精确路由和同一状态多个view同时更新    abstract: boolean (default:false) // 抽象路由  });

$urlRouterProvider

  • otherwise
  • when

 $urlRouterProvider.otherwise('/index'); // 路由无法匹配默认跳转地址  
 $urlRouterProvider.when('A-URL','B-URL'); // 如果URL匹配A重定向到B  



$stateParams

Basic
url: '/contacts/:contactId'url: '/contacts/{contactId}'
Regex
url: '/contacts/{contactId:[0-9a-fA-F]{1,8}}' //Hexadecimals
Query
url: '/contacts?contactId&contactRegion' //Separate with '&'


//State URL:url: '/users/:id/details/{type}/{repeat:[0-9]+}?from&to'//Navigate to:'/users/123/details//0' //$stateParams will be{ id:'123', type:'', repeat:'0' } //Navigated to:'/users/123/details/default/0?from=there&to=here' //$stateParams will be{ id:'123', type:'default', repeat:'0',from:'there', to:'here' }

继承性



  • Scope中的属性和方法(Angular特性非UI-Router)
  • 'resolve' 依赖
  • 'data' 自定义数据

'resolve' 依赖


   .state('parent', {
      resolve:{
         resA:  function(){
            return {'value': 'A'};
         }
      },
      controller: function($scope, resA){
          $scope.resA = resA.value;
      }
   })
   .state('parent.child', {
      resolve:{
         resB: function(resA){
            return {'value': resA.value + 'B'};
         }
      },
      controller: function($scope, resA, resB){
          $scope.resA2 = resA.value;
          $scope.resB = resB.value;
      } 
Learn more about how resolves work.

继承自定义'data'

$stateProvider   .state('parent', {
      data:{
         customData1:  "Hello",
         customData2:  "World!"
      }
   })
   .state('parent.child', {
      data:{
         // customData1 inherited from 'parent' 
         // but we'll overwrite customData2
         customData2:  "UI-Router!"
      }
   });

$rootScope.$on('$stateChangeStart', function(event, toState){ 
    var greeting = toState.data.customData1 + " " + toState.data.customData2;
    console.log(greeting);
}) 

当 'parent' 被激活,输出 'Hello World!' 

当 'parent.child' 被激活,输出 'Hello UI-Router!' 

如何激活路由



1. $state.go()

2. 点击一个带有 ui-sref 的指令

3. 通过路由配置的url

$state.go()




myApp.controller('contactCtrl', ['$scope', '$state', 
  function($scope, $state){
     $scope.goToDetails = function(){
        $state.go('contact.details', {id: selectedId});
     }
  } 
Params...
1. state name
2. state params (可选)
3. options (可选)

路由Trees

“因为UI-Router为我们保存了一张路由树,
我们可以方便的在这树上玩耍。”

记住下面的符号!

^   向上
.   向下


Examples

Start          Middle          End   

Go to parent - $state.go('^')


Go to child - $state.go('.3')


Go to sibling - $state.go('^.1')


Absolute Path - $state.go('3.3')


LOL! - $state.go('^.^.2.1')

@

  • 相对视图
  • 绝对视图

抽象路由

Abstract States


  • 抽象状态无法直接激活
  • 抽象状态内须嵌套子路由
  • 子路由激活抽象状态


事件

(Events)


State Change Events

$stateChangeStart (event, toState, toParams, fromState, fromParams)
can e.preventDefault()
$stateNotFound (event, unfoundState, fromState, fromParams) 

$stateChangeSuccess (event, toState, toParams, fromState, fromParams)
$stateChangeError (event, toState, toParams, fromState, fromParams, error)

View Load Events

$viewContentLoading (event, viewConfig)
$viewContentLoaded (event)

Thanks!!



Resources


by Jeffrey Yu 

Inspiration from Tim Kindberg

AngularUI-Router Introduction

By Jeffrey Yu

AngularUI-Router Introduction

UI-Router is an angularjs replacement module for ngRoute. It builds upon ngRoute's features by adding nested views and states capabiliites as well as the ability to have multiple named views at any level in the state tree.

  • 1,208