LoginSignup
29
29

More than 5 years have passed since last update.

ui-routerでページタイトルを動的に変更する

Last updated at Posted at 2015-01-27

Anguarjsのシングルページアプリケーションで、viewを変更した時にページタイトルを変更する方法を説明します。

事前準備

今回はui-routerモジュールを使用します。
ターミナルから下記のコマンドを実行して、ui-routerをインストールします。(要bower)
angularjsも一緒にインストールされます。

$ bower install ui-router

viewの作成

ビューの変更を確認するために下記の3つのビューファイルを用意します。
index.htmlのtitle要素にpage-titleディレクティブを使用しています。

index.html
<!DOCTYPE html>
<html lang="ja" ng-app="myApp">

<head>
    <meta charset="UTF-8">
    <title page-title></title>
</head>

<body>

    <div ui-view></div>
    <script src="bower_components/angular/angular.min.js"></script>
    <script src="bower_components/ui-router/release/angular-ui-router.min.js"></script>
    <script src="app.js"></script>
</body>

</html>

home.html
<h1>Home</h1>
<p><a ui-sref="home">home</a></p>
<p><a ui-sref="login">login</a></p>
login.html
<h1>Login</h1>
<p><a ui-sref="home">home</a></p>
<p><a ui-sref="login">login</a></p>

app.jsの作成とstateの設定

angular.moduleでui.routerを指定してください。
$stateProviderの中にstateの設定を記述します。
titleに指定した文字列がstateのページタイトルになります。

app.js
'use strict';
angular.module('myApp', ['ui.router'])

.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/home');
  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: 'home.html',
      title: 'ホーム'
    })
    .state('login', {
      url: '/login',
      templateUrl: 'login.html',
      title: 'ログイン'
    });
});

pageTitleディレクティブを追記

pageTitleディレクティブを追記します。
stateの変更があった場合に、state.titleのテキストをセットするようにしています。

app.js
'use strict';
angular.module('myApp', ['ui.router'])

.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/home');
  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: 'home.html',
      title: 'ホーム'
    })
    .state('login', {
      url: '/login',
      templateUrl: 'login.html',
      title: 'ログイン'
    });
})

/**
 * ページタイトルをセットするディレクティブ
 */
.directive('pageTitle', function($rootScope) {
  return {
    link: function(scope, element) {
      var listener = function(event, state) {
        var pageTitle = '';
        if (state.title) {
          pageTitle = state.title + ' | SiteName';
          element.text(pageTitle);
        }
      };
      // stateの変更が完了した後に処理を実行
      $rootScope.$on('$stateChangeSuccess', listener);
    }
  };
});

ブラウザで確認

a要素のリンクをクリックしてstateを変更すると動的にタイトルが変更されます。

スクリーンショット 2015-01-27 9.57.21.png

29
29
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
29