LoginSignup
3
3

More than 5 years have passed since last update.

AngularJSで共通メニューを作る

Last updated at Posted at 2013-06-16

AngularJSで共通メニューを表示するための機能を作ってみました。
機能としては、リンクをクリックした時に、classを変更してカレントページをハイライトしています。

AngularJSのdirectiveを使って、作っています。

main.js
app.directive('activetab', ['$location', function(location) {

    return {
        restrict: 'C',
        link: function($scope, $element, $attrs) {
            var elementPath = $attrs.href.substring(1);
            $scope.$location = location;
            $scope.$watch('$location.path()', function(locationPath) {
                var locationDirArray = locationPath.split('/');
                if (elementPath === '/' + locationDirArray[1] + '/') {
                    $element.parent().addClass('active');
                } else {
                    $element.parent().removeClass('active');
                }
            });
        }
    };
}]);

こちらの Stackoverflowを参考にさせてもらいました。
少し改造したのは以下の2点です。

  • イベントが発生したelementではなく、その親のelementにclassを追加している
  • locationの第一階層のみ見るようにしている。

これは、僕の作っているサンプルが以下のようなURL構造で作っていたからです。

  • 一覧ページ /guestbook/
  • 登録ページ /guestbook/entry

一覧ページ、登録ページ共に同じメニューがハイライトされて欲しかったので、URLの第一階層のみ見るようにしています。
親のelementにclassを追加しているのは、cssの都合で、a tagの親のli tagにclassを追加する必要があったからです。

上記のdirectiveを設定しているhtmlのサンプルです。
a tagのclassにdirectiveを設定しています。
これで、URLが変更された時に、a tabのhrefとURLの第一階層が一致していれば、a tagの親のli tagのclassにactiveが追加されます。

index.html
<ul class="nav">
    <li><a href="#/guestbook/" class="activetab">GuestBook</a></li>
</ul>

上記のサンプルはGithubに置いてます。

改訂版の記事を書きました。

3
3
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
3
3