LoginSignup
2
3

More than 5 years have passed since last update.

YEOMAN + angularJSでヘッダメニューにactiveクラスを自動付与する

Last updated at Posted at 2015-05-19

やりたいこと

ヘッダーのメニュー部分において、アクセスしているページに対応したハイライトを行いたい。

  • ルートにいるときはHomeがハイライトされる
    Homeのハイライト

  • AboutページにいるときはAboutがハイライトされる
    Aboutのハイライト

環境

  • YEOMANをいれたばっかり
    • angularJS
    • grunt
    • bower

流れ

  1. controllerにアクセスしているページのpathを取得
  2. 取得した文字列とメニューの内容が合致するかチェックし、合致するメニューのliタグにactiveクラスを付与

Controllerにアクセスしているページのpathを取得

controllers/main.js
angular.module('myApp')
  .controller('MainCtrl', function ($scope, $location) {
    $scope.isActive = function (viewLocation) {
         var active = (viewLocation === $location.path());
         return active;
    };
  });

$location.path()で今アクセスしているページのpathを取得できます。
もし、isActiveで投げた文字列とpathが合致していたら、trueが帰ってきます。

取得した文字列とメニューの内容が合致するかチェックし、合致するメニューのliタグにactiveクラスを付与

index.html
<ul class="nav navbar-nav" ng-controller="MainCtrl">
  <li ng-class="{ active: isActive('/') }"><a href="#/">Home</a></li>
  <li ng-class="{ active: isActive('/about') }"><a ng-href="#/about">About</a></li>
  <li ng-class="{ active: isActive('/contact') }"><a ng-href="#/">Contact</a></li>
</ul>

ng-controllerでMainCtrlを指定して、その中で先ほど記述したisActiveを呼び出します。
trueであれば、activeクラスがliタグに付与されます。

所感

今回は右も左も分からない状況だったので、MainCtrlに書いて操作していますが、タブメニューはウェブサイト全体に及ぶものなので、より正しい書くべき場所・書き方があると思います。(;´Д`)
MainCtrlにたくさん書くことになったら重く?なりそうだし...
やはりapp.jsに書くべきなのかな...

activeクラスを付与する方法が掲載されているサイトはたくさんあったのですが、とりあえずYEOMANいれたけどcontrollerって何〜〜〜から入ったので、そんな人のために投稿しました。

参考

How do I implement the bootstrap navbar active class with Angular JS - Stackoverflow

2
3
2

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