angular-ui-router使用

angular-ui-router使用

github源碼地址:https://github.com/angular-ui/ui-router

api地址 http://angular-ui.github.io/ui-router/site

安裝

npm install --save angular-ui-router

使用angular-ui-router

備註: 如下全部示例代碼來源於我的所寫的練習.javascript

地址爲:https://github.com/silence717/angular-webpack-demohtml

導入angular-ui-router
import uiRouter from 'angular-ui-router';
在angular.module中注入angular-ui-router
angular.module('app',[uiRouter]);
爲了方便使用,將$state與$stateParams所有掛載到$rootScope,在angular.module中初始化
function runBlock($rootScope, $state, $stateParams) {
    'ngInject';

    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
}
定義路由規則,在angular.module中配置路由規則
export function routerConfig($urlRouterProvider) {
    'ngInject';

    // 默認路由設置
    $urlRouterProvider.otherwise('/home');

    // 無視瀏覽器中 url末尾的"/"
    // 設置時 url, 末尾不要添加 "/"
    $urlRouterProvider.rule(($injector, $location) => {
        const path = $location.path();
        const hashTrailingSlash = path[path.length -1] === '/';

        if (hashTrailingSlash) {
            return path.slice(0, path.length -1);
        }
    });
}
基於以上兩部分的操做,完整的app初始化代碼爲
angular
    .module('app', [uiRouter])
    .config(routerConfig)
    .run(runBlock);
業務模塊路由定義配置,咱們一般建議將路由分散到本身的模塊管理,因此只以單個做爲示例
export const HomeRouter = {
    state: 'home',
    config: {
        url: '/home',
        views: {
            '@': {
                template: homeTpl,
                controller: 'HomeController',
                controllerAs: 'vm'
            }
        },
        title: '好玩的app'
    }
};
業務入口主文件導入,而且在angular.module中配置
import {HomeRouter} from './Routers';

function config($stateProvider) {
    'ngInject';
    $stateProvider.state(HomeRouter.state, HomeRouter.config);
}

export default angular
    .module('app.home', [])
    .config(config)
    .name;
頁面的html如何書寫
<ul class="nav navbar-nav">
    <li ui-sref-active="active"><a ui-sref="home">首頁</a></li>
    <li ui-sref-active="active"><a ui-sref="album">相冊</a></li>
    <li ui-sref-active="active"><a ui-sref="user.baseInfo">我的中心</a></li>
</ul>
<div ui-view=""></div>

在這裏作一個簡單經常使用的API的解釋

directive

ui-sref:A directive that binds a link ( tag) to a state.
ui-sref-active: A directive working alongside ui-sref to add classes to an element when the related ui-sref directive's state is active, and removing them when it is inactive.
ui-view: The ui-view directive tells $state where to place your templates.

ui-view使用有三種,分別爲:java

  1. as element:webpack

<ui-view></ui-view>
  1. as attribute:git

<ANY ui-view ></ANY>
  1. as class:github

<ANY class="ui-view"></ANY>

具體裏面的參數不作介紹,本身查閱官方文檔web

上面的html代碼會被compile爲:npm

<ul class="nav navbar-nav">
    <li ui-sref-active="active" ui-sref-active-eq="" class="active"><a ui-sref="home" href="#/home">首頁</a></li>
    <li ui-sref-active="active" class=""><a ui-sref="album" href="#/album">相冊</a></li>
    <li ui-sref-active="active" class=""><a ui-sref="user.baseInfo" href="#/user/baseInfo">我的中心</a></li>
</ul>

$state使用

Methods

get 獲取當前state的配置信息
<a href="javascript:;" ng-click="vm.getConfig();">獲取state配置</a>
let config = this.state.get('user');
    console.log(config);
    // => Object {url: "/user", views: Object, title: "我的中心", name: "user"}...
go 跳轉到一個新的state
<a href="javascript:;" ng-click="vm.goUserCenter();">這是一個跳轉連接...</a>
// 不帶參數跳轉
    this.state.go('user.baseInfo');
    // 帶參數跳轉
    this.state.go('album.detail', {id: 1});
href 獲取到當前state的href值
console.log(this.state.href('album.detail', {id: 0}));
    // => #/album/0
includes 獲取當前state是否包含某些state
console.log(this.state.includes('album'));
    // => false
is Similar to $state.includes, but only checks for the full state name
console.log(this.state.is('home'));   //=> true

events

$stateChangeStart 路由發生改變
function stateChangeStart($rootScope) {
    $rootScope.$on('$stateChangeStart',
        (event, toState, toParams, fromState, fromParams) => {
            // event.preventDefault();
            console.log('開始改變=====');
            console.log(toState);
            console.log(toParams);
            console.log(fromState);
            console.log(fromParams);
            // 開始改變=====
            // app.js:48Object {url: "/home", views: Object, title: "好玩的app", name: "home"}
            // app.js:49Object {}
            // app.js:50Object {name: "", url: "^", views: null, abstract: true}
            // app.js:51Object {}
            // client.js:55 [HMR] connected
        });
}
$stateChangeError 路由轉變出錯,參數基本與$stateChangeStart一致,多一個error參數
$stateChangeSuccess 路由轉向成功,參數與$stateChangeStart徹底一致
$stateNotFound 未找到路由,demo copy於參照官網
// somewhere, assume lazy.state has not been defined
$state.go("lazy.state", {a:1, b:2}, {inherit:false});

// somewhere else
$scope.$on('$stateNotFound',
function(event, unfoundState, fromState, fromParams) {
    console.log(unfoundState.to); // "lazy.state"
    console.log(unfoundState.toParams); // {a:1, b:2}
    console.log(unfoundState.options); // {inherit:false} + default options
})
onEnter 能夠配置進入路由to do something
onEnter: function() {
    console.log('enter user.footprint state');
}
onExit 退出路由作什麼
onExit: function() {
    // 用於初始化一些數據什麼的,清空表單...
    console.log('exit user.footprint state');
}

部分知識點單列:

1、問: 多個頁面可能使用相同的html模板,咱們是要一樣的代碼寫N遍嗎? 答案確定不是.那麼問題來了,一個頁面有多個模板文件,腫麼辦?

  1. 在html中給ui-view添加名字api

<div ui-view="content"></div>
<div ng-show="vm.isShowThumb" class="module-content"  ui-view="thumbList"></div>
<div ng-show="vm.isShowDetail" ui-view="detailList"></div>
  1. 在路由配置中添加配置信息瀏覽器

export const UserFootprintRouter = {
    state: 'user.footprint',
    config: {
        url: '/footprint',
        views: {
            'content@user': {
                template: footPrintTpl,
                controller: 'FootprintController',
                controllerAs: 'vm'
            },
            'thumbList@user.footprint': {
                template: thumbListTpl
            },
            'detailList@user.footprint': {
                template: detailListTpl
            }
        },
        title: '個人足跡'
    }
};

我的理解就是: viewname@statename去設置template

2、 $stateParams使用,^^最後一個點

先看代碼:

export const AlbumDetailRouter = {
    state: 'album.detail',
    config: {
        url: '/:id',
        views: {
            '@': {
                template: albumDetailTpl,
                controller: 'PhotoController',
                controllerAs: 'vm'
            }
        },
        title: '單張照片show'
    }
};

問: 咱們常常會須要用到路由去傳參,例如編輯一條信息,獲取單個信息,應該如何去作呢?

答: angular-ui-router提供了一個$stateParams的service,可直接獲取.在controller中的使用示例

export default class PhotoController {

    constructor(photoResource, $stateParams) {

        let vm = this;

        photoResource.success(data => {
            vm.detail = data[$stateParams.id];
        })
    }
}

有人確定會疑問,$stateParams從何而來,在上面咱們給angular.module中已經將其初始化,掛在到$rootScope.

3、此次真的是最後一個點了 most important: $urlRouterProvider

  1. when() for redirection

app.config(function($urlRouterProvider){
        $urlRouterProvider.when('', '/index');
    });
  1. otherwise() for invalid routes

app.config(function($urlRouterProvider){
    $urlRouterProvider.otherwise('/home');
});
it's over! 全部以上僅表明我的理解,若有不對,請指出,虛心接受改正錯誤!
相關文章
相關標籤/搜索