2016.5.30
2017.6.6

ルーティングのイベント(ui-router)

AngularJSのui-routerでルーティングを行っている場合に、使用できるイベントの一覧をメモしておきます。

目次

  • $stateChangeStart
  • $stateNotFound
  • $stateChangeSuccess
  • $stateChangeError
  • $viewContentLoading
  • $viewContentLoaded

$stateChangeStart

ページ遷移処理の開始時に発火


$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams, options){ 
    console.log(toState); // {"url":"article/:id/","templateUrl":"views/article.html","controller":"ArticleCtrl","name":"root.search.article"}
    console.log(toParams); // {"id":"60"}
    console.log(fromState); // {"url":":cid/:tid/?pg","templateUrl":"views/search.list.html","controller":"SearchListCtrl","name":"root.search.list"}
    console.log(fromParams); // {"cid":"top","tid":"all"}
    console.log(options); // {"location":false,"inherit":true,"relative":null,"notify":true,"reload":false,"$retry":false}

    event.preventDefault(); // 発火したイベントのキャンセル
});

$stateNotFound

stateが存在しなかった場合に発火(ui-srefで指定したstateが存在しなかった場合など)


// 存在しないページへ遷移
$state.go("lazy.state", {a:1, b:2}, {inherit:false});

// ページが存在しなかった場合の処理
$rootScope.$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
})

$stateChangeSuccess

ページ遷移処理の成功時に発火


$rootScope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ 
    console.log(toState); // {"url":"article/:id/","templateUrl":"views/article.html","controller":"ArticleCtrl","name":"root.search.article"}
    console.log(toParams); // {"id":"60"}
    console.log(fromState); // {"url":":cid/:tid/?pg","templateUrl":"views/search.list.html","controller":"SearchListCtrl","name":"root.search.list"}
    console.log(fromParams); // {"cid":"top","tid":"all"}
});

$stateChangeError

ページ遷移エラー時に発火(templateUrlに指定したファイルが存在しなかった場合など)


$rootScope.$on('$stateChangeError', 
function(event, toState, toParams, fromState, fromParams, error){ 
    console.log(toState); // {"url":"article/:id/","templateUrl":"views/article.html","controller":"ArticleCtrl","name":"root.search.article"}
    console.log(toParams); // {"id":"60"}
    console.log(fromState); // {"url":":cid/:tid/?pg","templateUrl":"views/search.list.html","controller":"SearchListCtrl","name":"root.search.list"}
    console.log(fromParams); // {"cid":"top","tid":"all"}
    console.log(error); // エラー情報
});

$viewContentLoading

DOMがレンダリングされる前に発火


$rootScope.$on('$viewContentLoading', 
function(event, viewConfig){ 
    console.log(viewConfig); // state情報。「@」「@root」「@root.search」など。
});

$viewContentLoaded

DOMがレンダリングされた後に発火(このイベントは$scopeに対して)


$scope.$on('$viewContentLoaded', 
function(event){ 
});

AngularJS】関連記事