145

我在AngularJS中设置了这样的路线:

$routeProvider
    .when('/dashboard', {templateUrl:'partials/dashboard', controller:widgetsController})
    .when('/lab', {templateUrl:'partials/lab', controller:widgetsController})

我在顶部栏上有一些链接样式为选项卡。如何根据当前模板或网址将“活动”类添加到选项卡?

4

18 回答 18

275

无需依赖 URL 即可解决此问题的一种方法是在$routeProvider配置期间为每个部分添加自定义属性,如下所示:

$routeProvider.
    when('/dashboard', {
        templateUrl: 'partials/dashboard.html',
        controller: widgetsController,
        activetab: 'dashboard'
    }).
    when('/lab', {
        templateUrl: 'partials/lab.html',
        controller: widgetsController,
        activetab: 'lab'
    });

$route在您的控制器中公开:

function widgetsController($scope, $route) {
    $scope.$route = $route;
}

active根据当前活动选项卡设置类:

<li ng-class="{active: $route.current.activetab == 'dashboard'}"></li>
<li ng-class="{active: $route.current.activetab == 'lab'}"></li>
于 2012-09-25T15:28:18.180 回答
134

一种方法是使用 ngClass 指令和 $location 服务。在您的模板中,您可以执行以下操作:

ng-class="{active:isActive('/dashboard')}"

whereisActive将是这样定义的范围内的函数:

myApp.controller('MyCtrl', function($scope, $location) {
    $scope.isActive = function(route) {
        return route === $location.path();
    }
});

这是完整的 jsFiddle:http: //jsfiddle.net/pkozlowski_opensource/KzAfG/

在每个导航选项卡上重复ng-class="{active:isActive('/dashboard')}"可能会很乏味(如果您有很多选项卡),因此此逻辑可能是非常简单指令的候选者。

于 2012-09-06T18:23:31.953 回答
41

遵循 Pavel 使用自定义指令的建议,这是一个不需要向 routeConfig 添加任何有效负载的版本,它是超级声明性的,并且可以通过简单地更改slice()您关注的路径来适应任何级别的路径.

app.directive('detectActiveTab', function ($location) {
    return {
      link: function postLink(scope, element, attrs) {
        scope.$on("$routeChangeSuccess", function (event, current, previous) {
            /*  
                Designed for full re-usability at any path, any level, by using 
                data from attrs. Declare like this: 
                <li class="nav_tab">
                  <a href="#/home" detect-active-tab="1">HOME</a>
                </li> 
            */

            // This var grabs the tab-level off the attribute, or defaults to 1
            var pathLevel = attrs.detectActiveTab || 1,
            // This var finds what the path is at the level specified
                pathToCheck = $location.path().split('/')[pathLevel] || 
                  "current $location.path doesn't reach this level",
            // This var finds grabs the same level of the href attribute
                tabLink = attrs.href.split('/')[pathLevel] || 
                  "href doesn't include this level";
            // Above, we use the logical 'or' operator to provide a default value
            // in cases where 'undefined' would otherwise be returned.
            // This prevents cases where undefined===undefined, 
            // possibly causing multiple tabs to be 'active'.

            // now compare the two:
            if (pathToCheck === tabLink) {
              element.addClass("active");
            }
            else {
              element.removeClass("active");
            }
        });
      }
    };
  });

我们通过监听$routeChangeSuccess事件来实现我们的目标,而不是通过$watch在路径上放置一个。我相信这意味着逻辑应该不那么频繁地运行,因为我认为每个$digest周期都会触发手表。

通过在指令声明中传递路径级参数来调用它。这指定了当前 $location.path() 的哪个块你想要匹配你的href属性。

<li class="nav_tab"><a href="#/home" detect-active-tab="1">HOME</a></li>

因此,如果您的选项卡应该对路径的基本级别做出反应,请将参数设为“1”。因此,当 location.path() 为“/home”时,它将匹配href. 如果您有应该对路径的第二级、第三级或第 11 级作出反应的选项卡,请相应地进行调整。这种从 1 或更大的切片将绕过 href 中的恶意“#”,它位于索引 0 处。

唯一的要求是您调用 an <a>,因为该元素假定存在一个href属性,它将与当前路径进行比较。但是,如果您更喜欢在 or 上调用,您可以相当容易地适应读取/写入父元素或子元素<li>。我挖掘这一点是因为您可以通过简单地改变 pathLevel 参数在许多情况下重复使用它。如果在逻辑中假设要读取的深度,则需要多个版本的指令才能与导航的多个部分一起使用。


编辑 3/18/14:该解决方案没有得到充分概括,如果您为 'activeTab' 的值定义了一个 arg,该 arg 针对undefined$location.path()元素的href. 因为:undefined === undefined。更新以修复该情况。

在处理这个问题时,我意识到应该有一个可以在父元素上声明的版本,其模板结构如下:

<nav id="header_tabs" find-active-tab="1">
    <a href="#/home" class="nav_tab">HOME</a>
    <a href="#/finance" class="nav_tab">Finance</a>
    <a href="#/hr" class="nav_tab">Human Resources</a>
    <a href="#/quarterly" class="nav_tab">Quarterly</a>
</nav>

请注意,此版本不再类似于 Bootstrap 样式的 HTML。但是,它更现代,使用的元素更少,所以我偏爱它。这个版本的指令,加上原来的,现在可以在 Github 上作为一个插件模块使用,您可以将其声明为依赖项。如果有人真的使用它们,我很乐意对它们进行 Bower-ize。

此外,如果你想要一个包含<li>'s 的引导兼容版本,你可以使用 angular-ui-bootstrap Tabs 模块,我认为它是在这篇原始帖子之后出现的,它可能比这篇更具声明性。它对于基本的东西不太简洁,但为您提供了一些额外的选项,例如禁用的选项卡和激活和停用时触发的声明性事件。

于 2013-07-05T20:01:31.347 回答
27

@rob-juurlink 我对您的解决方案进行了一些改进:

而不是每条路线都需要一个活动标签;并且需要在每个控制器中设置活动选项卡我这样做:

var App = angular.module('App',[]);
App.config(['$routeProvider', function($routeProvider){
  $routeProvider.
  when('/dashboard', {
    templateUrl: 'partials/dashboard.html',
    controller: Ctrl1
  }).
  when('/lab', {
    templateUrl: 'partials/lab.html',
    controller: Ctrl2
  });
}]).run(['$rootScope', '$location', function($rootScope, $location){
   var path = function() { return $location.path();};
   $rootScope.$watch(path, function(newVal, oldVal){
     $rootScope.activetab = newVal;
   });
}]);

HTML 看起来像这样。activetab 只是与该路由相关的 url。这只是消除了在每个控制器中添加代码的需要(如果这是使用它们的唯一原因,则拖入 $route 和 $rootScope 等依赖项)

<ul>
    <li ng-class="{active: activetab=='/dashboard'}">
       <a href="#/dashboard">dashboard</a>
    </li>
    <li ng-class="{active: activetab=='/lab'}">
       <a href="#/lab">lab</a>
    </li>
</ul>
于 2013-03-27T12:09:56.723 回答
16

也许这样的指令可能会解决您的问题:http: //jsfiddle.net/p3ZMR/4/

HTML

<div ng-app="link">
<a href="#/one" active-link="active">One</a>
<a href="#/two" active-link="active">One</a>
<a href="#" active-link="active">home</a>


</div>

JS

angular.module('link', []).
directive('activeLink', ['$location', function(location) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, controller) {
            var clazz = attrs.activeLink;
            var path = attrs.href;
            path = path.substring(1); //hack because path does bot return including hashbang
            scope.location = location;
            scope.$watch('location.path()', function(newPath) {
                if (path === newPath) {
                    element.addClass(clazz);
                } else {
                    element.removeClass(clazz);
                }
            });
        }

    };

}]);
于 2012-09-27T22:53:08.083 回答
14

这里最简单的解决方案:

如何使用 Angular JS 设置引导导航栏活动类?

这是:

使用 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();
    };
}
于 2014-06-23T17:33:32.637 回答
12

我建议使用state.ui 模块,它不仅支持多个和嵌套视图,而且使这种工作非常容易(引用下面的代码):

<ul class="nav">
    <li ng-class="{ active: $state.includes('contacts') }"><a href="#{{$state.href('contacts')}}">Contacts</a></li>
    <li ng-class="{ active: $state.includes('about') }"><a href="#{{$state.href('about')}}">About</a></li>
</ul>

值得一读。

于 2013-08-01T00:39:10.007 回答
4

这是另一个版本的 XMLillis,带有 domi 的 LI 更改,它使用搜索字符串而不是路径级别。我认为这对我的用例来说更明显。

statsApp.directive('activeTab', function ($location) {
  return {
    link: function postLink(scope, element, attrs) {
      scope.$on("$routeChangeSuccess", function (event, current, previous) {
        if (attrs.href!=undefined) { // this directive is called twice for some reason
          // The activeTab attribute should contain a path search string to match on.
          // I.e. <li><a href="#/nested/section1/partial" activeTab="/section1">First Partial</a></li>
          if ($location.path().indexOf(attrs.activeTab) >= 0) {
            element.parent().addClass("active");//parent to get the <li>
          } else {
            element.parent().removeClass("active");
          }
        }
      });
    }
  };
});

HTML 现在看起来像:

<ul class="nav nav-tabs">
  <li><a href="#/news" active-tab="/news">News</a></li>
  <li><a href="#/some/nested/photos/rawr" active-tab="/photos">Photos</a></li>
  <li><a href="#/contact" active-tab="/contact">Contact</a></li>
</ul>
于 2013-08-29T16:11:42.840 回答
3

我发现 XMLilley 的 anwser 是最好的、适应性最强的和非侵入性的。

但是我有一个小故障。

为了与引导导航一起使用,我修改它的方法如下:

app.directive('activeTab', function ($location) {
    return {
      link: function postLink(scope, element, attrs) {
        scope.$on("$routeChangeSuccess", function (event, current, previous) {
            /*  designed for full re-usability at any path, any level, by using 
                data from attrs
                declare like this: <li class="nav_tab"><a href="#/home" 
                                   active-tab="1">HOME</a></li> 
            */
            if(attrs.href!=undefined){// this directive is called twice for some reason
                // this var grabs the tab-level off the attribute, or defaults to 1
                var pathLevel = attrs.activeTab || 1,
                // this var finds what the path is at the level specified
                    pathToCheck = $location.path().split('/')[pathLevel],
                // this var finds grabs the same level of the href attribute
                    tabLink = attrs.href.split('/')[pathLevel];
                // now compare the two:
                if (pathToCheck === tabLink) {
                  element.parent().addClass("active");//parent to get the <li>
                }
                else {
                  element.parent().removeClass("active");
                }
            }
        });
      }
    };
  });

我添加了“if(attrs.href!=undefined)”,因为这个函数被调用了两次,第二次产生了错误。

至于html:

<ul class="nav nav-tabs">
   <li class="active" active-tab="1"><a href="#/accueil" active-tab="1">Accueil</a></li>
   <li><a active-tab="1" href="#/news">News</a></li>
   <li><a active-tab="1" href="#/photos" >Photos</a></li>
   <li><a active-tab="1" href="#/contact">Contact</a></li>
</ul>
于 2013-08-15T13:09:52.017 回答
3

引导示例。

如果您使用的是 Angulars 内置路由 (ngview),则可以使用此指令:

angular.module('myApp').directive('classOnActiveLink', [function() {
    return {
        link: function(scope, element, attrs) {

            var anchorLink = element.children()[0].getAttribute('ng-href') || element.children()[0].getAttribute('href');
            anchorLink = anchorLink.replace(/^#/, '');

            scope.$on("$routeChangeSuccess", function (event, current) {
                if (current.$$route.originalPath == anchorLink) {
                    element.addClass(attrs.classOnActiveLink);
                }
                else {
                    element.removeClass(attrs.classOnActiveLink);
                }
            });

        }
    };
}]);

假设您的标记如下所示:

    <ul class="nav navbar-nav">
        <li class-on-active-link="active"><a href="/orders">Orders</a></li>
        <li class-on-active-link="active"><a href="/distributors">Distributors</a></li>
    </ul>

我喜欢这样做,因为您可以在属性中设置所需的类名。

于 2014-11-23T09:59:48.373 回答
2

您也可以简单地将位置注入范围并使用它来扣除导航的样式:

function IndexController( $scope, $rootScope, $location ) {
  $rootScope.location = $location;
  ...
}

然后在你的ng-class

<li ng-class="{active: location.path() == '/search'}">
  <a href="/search">Search><a/>
</li>
于 2013-02-01T14:50:23.580 回答
2

另一种方法是使用ui-sref-active

与 ui-sref 一起工作的指令,用于在相关 ui-sref 指令的状态为活动时向元素添加类,并在相关的 ui-sref 指令的状态为非活动时删除它们。主要用例是简化依赖 ui-sref 的导航菜单的特殊外观,通过使“活动”状态的菜单按钮看起来不同,将其与非活动菜单项区分开来。

用法:

ui-sref-active='class1 class2 class3' - 当相关的 ui-sref 的状态为活动时,类 "class1"、"class2" 和 "class3" 分别添加到指令元素中,并在其非活动时删除。

示例:
给定以下模板,

<ul>
  <li ui-sref-active="active" class="item">
    <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  </li>
  <!-- ... -->
</ul>

当应用程序状态为“app.user”并包含状态参数“user”和值为“bilbobaggins”时,生成的 HTML 将显示为

<ul>
  <li ui-sref-active="active" class="item active">
    <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
  </li>
  <!-- ... -->
</ul>

类名在指令链接期间被插值一次(对插值值的任何进一步更改都将被忽略)。可以以空格分隔的格式指定多个类。

使用 ui-sref-opts 指令将选项传递给 $state.go()。例子:

<a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
于 2016-02-01T13:57:02.457 回答
1

我同意 Rob 关于在控制器中有自定义属性的帖子。显然我没有足够的代表发表评论。这是请求的jsfiddle:

示例 html

<div ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="link in links" ng-class="{active: $route.current.activeNav == link.type}"> <a href="{{link.uri}}">{{link.name}}</a>

        </li>
    </ul>
</div>

示例 app.js

angular.module('MyApp', []).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/a', {
        activeNav: 'a'
    })
        .when('/a/:id', {
        activeNav: 'a'
    })
        .when('/b', {
        activeNav: 'b'
    })
        .when('/c', {
        activeNav: 'c'
    });
}])
    .controller('MyCtrl', function ($scope, $route) {
    $scope.$route = $route;
    $scope.links = [{
        uri: '#/a',
        name: 'A',
        type: 'a'
    }, {
        uri: '#/b',
        name: 'B',
        type: 'b'
    }, {
        uri: '#/c',
        name: 'C',
        type: 'c'
    }, {
        uri: '#/a/detail',
        name: 'A Detail',
        type: 'a'
    }];
});

http://jsfiddle.net/HrdR6/

于 2013-03-13T21:18:24.657 回答
1
'use strict';

angular.module('cloudApp')
  .controller('MenuController', function ($scope, $location, CloudAuth) {
    $scope.menu = [
      {
        'title': 'Dashboard',
        'iconClass': 'fa fa-dashboard',
        'link': '/dashboard',
        'active': true
      },
      {
        'title': 'Devices',
        'iconClass': 'fa fa-star',
        'link': '/devices'
      },
      {
        'title': 'Settings',
        'iconClass': 'fa fa-gears',
        'link': '/settings'
      }
    ];
    $location.path('/dashboard');
    $scope.isLoggedIn = CloudAuth.isLoggedIn;
    $scope.isAdmin = CloudAuth.isAdmin;
    $scope.isActive = function(route) {
      return route === $location.path();
    };
  });

并在模板中使用以下内容:

<li role="presentation" ng-class="{active:isActive(menuItem.link)}" ng-repeat="menuItem in menu"><a href="{{menuItem.link}}"><i class="{{menuItem.iconClass}}"></i>&nbsp;&nbsp;{{menuItem.title}}</a></li>
于 2015-06-03T23:04:21.797 回答
0

我需要一个不需要更改控制器的解决方案,因为对于某些页面,我们只呈现模板并且根本没有控制器。感谢之前建议使用的评论者,$routeChangeSuccess我想出了这样的东西:

# Directive
angular.module('myapp.directives')
.directive 'ActiveTab', ($route) ->
  restrict: 'A'

  link: (scope, element, attrs) ->
    klass = "active"

    if $route.current.activeTab? and attrs.flActiveLink is $route.current.activeTab
      element.addClass(klass)

    scope.$on '$routeChangeSuccess', (event, current) ->
      if current.activeTab? and attrs.flActiveLink is current.activeTab
        element.addClass(klass)
      else
        element.removeClass(klass)

# Routing
$routeProvider
.when "/page",
  templateUrl: "page.html"
  activeTab: "page"
.when "/other_page",
  templateUrl: "other_page.html"
  controller: "OtherPageCtrl"
  activeTab: "other_page"

# View (.jade)
a(ng-href='/page', active-tab='page') Page
a(ng-href='/other_page', active-tab='other_page') Other page

它不依赖于 URL,因此为任何子页面等设置它真的很容易。

于 2013-10-25T13:57:02.190 回答
0

我不记得我在哪里找到了这种方法,但它非常简单并且效果很好。

HTML:

<nav role="navigation">
    <ul>
        <li ui-sref-active="selected" class="inactive"><a ui-sref="tab-01">Tab 01</a></li> 
        <li ui-sref-active="selected" class="inactive"><a ui-sref="tab-02">Tab 02</a></li>
    </ul>
</nav>

CSS:

  .selected {
    background-color: $white;
    color: $light-blue;
    text-decoration: none;
    border-color: $light-grey;
  } 
于 2016-04-12T14:20:34.710 回答
0

如果您使用 ngRoute(用于路由),那么您的应用程序将具有以下配置,

angular
  .module('appApp', [
    'ngRoute'
 ])
config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        controllerAs: 'main'
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl',
        controllerAs: 'about'
      })
}
});

现在,只需在此配置中添加一个控制器,如下所示,

angular
      .module('appApp', [
        'ngRoute'
     ])
    config(function ($routeProvider) {
        $routeProvider
          .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl',
            activetab: 'main'
          })
          .when('/about', {
            templateUrl: 'views/about.html',
            controller: 'AboutCtrl',
            activetab: 'about'
          })
    }
    })
  .controller('navController', function ($scope, $route) {
    $scope.$route = $route;
  });

正如您在配置中提到的活动选项卡一样,现在您只需在<li>or<a>标记中添加活动类。像,

ng-class="{active: $route.current.activetab == 'about'}"

这意味着,每当用户单击关于页面时,这将自动识别当前选项卡并应用活动的 css 类。

我希望这有帮助!

于 2018-06-06T12:57:36.890 回答
-3

来这里寻求解决方案..虽然上述解决方案工作正常,但发现它们有点复杂,没有必要。对于仍在寻找简单而整洁的解决方案的人来说,它将完美地完成任务。

<section ng-init="tab=1">
                <ul class="nav nav-tabs">
                    <li ng-class="{active: tab == 1}"><a ng-click="tab=1" href="#showitem">View Inventory</a></li>
                    <li ng-class="{active: tab == 2}"><a ng-click="tab=2" href="#additem">Add new item</a></li>
                    <li ng-class="{active: tab == 3}"><a ng-click="tab=3" href="#solditem">Sold item</a></li>
                </ul>
            </section>
于 2015-07-19T12:04:04.567 回答