问题

如果我有一个navbar在引导与项目

Home | About | Contact

如何为活动的每个菜单项设置活动类?也就是说,当角路由在

时,如何设置 class =“active”

  1. #/ for home
  2. #/about for the about page
  3. #/contact for the contact page


解决方法

一个非常优雅的方法是使用ng-controller在ng-view之外运行单个控制器:

<div class="collapse navbar-collapse" ng-controller="HeaderController">
    <ul class="nav navbar-nav">
        <li ng-class="{ active: isActive('/')}"><a href="/">Home</a></li>
        <li ng-class="{ active: isActive('/dogs')}"><a href="/dogs">Dogs</a></li>
        <li ng-class="{ active: isActive('/cats')}"><a href="/cats">Cats</a></li>
    </ul>
</div>
<div ng-view></div>

并包含在controllers.js:

function HeaderController($scope, $location) 
{ 
    $scope.isActive = function (viewLocation) { 
        return viewLocation === $location.path();
    };
}



相关问题推荐