206

AngularJS 是否有助于在active当前页面的链接上设置一个类?

我想有一些神奇的方式可以做到这一点,但我似乎找不到。

我的菜单如下所示:

 <ul>
   <li><a class="active" href="/tasks">Tasks</a>
   <li><a href="/actions">Tasks</a>
 </ul>

我的路线中有每个控制器的控制器:TasksControllerActionsController.

但是我想不出一种将a链接上的“活动”类绑定到控制器的方法。

有什么提示吗?

4

29 回答 29

266

正在查看

<a ng-class="getClass('/tasks')" href="/tasks">Tasks</a>

在控制器上

$scope.getClass = function (path) {
  return ($location.path().substr(0, path.length) === path) ? 'active' : '';
}

有了这个,任务链接将在任何以'/tasks'开头的url中都有活动类(例如'/tasks/1/reports')

于 2012-09-25T23:46:44.670 回答
86

我建议在链接上使用指令。

但它还不完美。当心hashbangs ;)

这是指令的javascript:

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 not return including hashbang
        scope.location = location;
        scope.$watch('location.path()', function (newPath) {
          if (path === newPath) {
            element.addClass(clazz);
          } else {
            element.removeClass(clazz);
          }
        });
      }
    };
  }]);

以下是它在 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>

之后使用 css 进行样式设置:

.active { color: red; }
于 2012-09-27T22:38:27.463 回答
48

这是一种适用于 Angular 的简单方法。

<ul>
    <li ng-class="{ active: isActive('/View1') }"><a href="#/View1">View 1</a></li>
    <li ng-class="{ active: isActive('/View2') }"><a href="#/View2">View 2</a></li>
    <li ng-class="{ active: isActive('/View3') }"><a href="#/View3">View 3</a></li>
</ul>

在您的 AngularJS 控制器中:

$scope.isActive = function (viewLocation) {
     var active = (viewLocation === $location.path());
     return active;
};

该线程有许多其他类似的答案。

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

于 2013-09-25T01:32:59.317 回答
33

只是为了在辩论中增加我的两分钱,我制作了一个纯角度模块(没有 jQuery),它也适用于包含数据的哈希 url。(例如#/this/is/path?this=is&some=data

您只需将模块作为依赖项添加auto-active到菜单的祖先之一。像这样:

<ul auto-active>
    <li><a href="#/">main</a></li>
    <li><a href="#/first">first</a></li>
    <li><a href="#/second">second</a></li>
    <li><a href="#/third">third</a></li>
</ul>

模块如下所示:

(function () {
    angular.module('autoActive', [])
        .directive('autoActive', ['$location', function ($location) {
        return {
            restrict: 'A',
            scope: false,
            link: function (scope, element) {
                function setActive() {
                    var path = $location.path();
                    if (path) {
                        angular.forEach(element.find('li'), function (li) {
                            var anchor = li.querySelector('a');
                            if (anchor.href.match('#' + path + '(?=\\?|$)')) {
                                angular.element(li).addClass('active');
                            } else {
                                angular.element(li).removeClass('active');
                            }
                        });
                    }
                }

                setActive();

                scope.$on('$locationChangeSuccess', setActive);
            }
        }
    }]);
}());

(你当然可以只使用指令部分)

还值得注意的是,这不适用于空散列(例如example.com/#或只是example.com),它需要至少example.com/#/或只是example.com#/. 但这会在 ngResource 之类的情况下自动发生。

这是小提琴:http: //jsfiddle.net/gy2an/8/

于 2014-03-09T12:23:28.383 回答
22

就我而言,我通过创建一个负责导航的简单控制器解决了这个问题

angular.module('DemoApp')
  .controller('NavigationCtrl', ['$scope', '$location', function ($scope, $location) {
    $scope.isCurrentPath = function (path) {
      return $location.path() == path;
    };
  }]);

只需将 ng-class 添加到元素中,如下所示:

<ul class="nav" ng-controller="NavigationCtrl">
  <li ng-class="{ active: isCurrentPath('/') }"><a href="#/">Home</a></li>
  <li ng-class="{ active: isCurrentPath('/about') }"><a href="#/about">About</a></li>
  <li ng-class="{ active: isCurrentPath('/contact') }"><a href="#/contact">Contact</a></li>
</ul>
于 2013-09-19T12:30:39.893 回答
14

对于AngularUI路由器用户:

<a ui-sref-active="active" ui-sref="app">

这将active在所选对象上放置一个类。

于 2014-04-08T17:35:56.037 回答
13

@Renan-tomal-fernandes的回答很好,但需要一些改进才能正常工作。事实上,它总是会检测到主页 ( / ) 的链接被触发,即使您在另一个部分。

所以我对其进行了一些改进,这是代码。我使用Bootstrap,所以活动部分在<li>元素中,而不是<a>.

控制器

$scope.getClass = function(path) {
    var cur_path = $location.path().substr(0, path.length);
    if (cur_path == path) {
        if($location.path().substr(0).length > 1 && path.length == 1 )
            return "";
        else
            return "active";
    } else {
        return "";
    }
}

模板

<div class="nav-collapse collapse">
  <ul class="nav">
    <li ng-class="getClass('/')"><a href="#/">Home</a></li>
    <li ng-class="getClass('/contents/')"><a href="#/contests/">Contents</a></li>
    <li ng-class="getClass('/data/')"><a href="#/data/">Your data</a></li>
  </ul>
</div>
于 2013-03-18T13:19:28.470 回答
13

有一个ng-class指令,它绑定变量和 css 类。它还接受对象(类名与布尔值对)。

这是示例,http ://plnkr.co/edit/SWZAqj

于 2012-09-25T23:53:13.547 回答
10

这是我在阅读了上面的一些优秀建议后提出的解决方案。在我的特殊情况下,我试图使用Bootstrap 选项卡组件作为我的菜单,但不想使用 Angular-UI 版本,因为我希望选项卡充当菜单,其中每个选项卡都可以添加书签,而不是作为单个页面导航的选项卡。(如果您对 Angular-UI 版本的引导选项卡的外观感兴趣,请参阅http://angular-ui.github.io/bootstrap/#/tabs )。

我真的很喜欢 kfis 关于创建自己的指令来处理这个问题的答案,但是有一个需要放置在每个链接上的指令似乎很麻烦。所以我创建了我自己的 Angular 指令,它被放置在ul. 以防万一其他人尝试做同样的事情,我想我会把它贴在这里,尽管正如我所说,上述许多解决方案也可以工作。就 javascript 而言,这是一个稍微复杂的解决方案,但它创建了一个具有最少标记的可重用组件。

这是指令的 javascript 和路由提供程序ng:view

var app = angular.module('plunker', ['ui.bootstrap']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/One', {templateUrl: 'one.html'}).
        when('/Two', {templateUrl: 'two.html'}).
        when('/Three', {templateUrl: 'three.html'}).
        otherwise({redirectTo: '/One'});
  }]).
  directive('navTabs', ['$location', function(location) {
    return {
        restrict: 'A',
        link: function(scope, element) {
            var $ul = $(element);
            $ul.addClass("nav nav-tabs");

            var $tabs = $ul.children();
            var tabMap = {};
            $tabs.each(function() {
              var $li = $(this);
              //Substring 1 to remove the # at the beginning (because location.path() below does not return the #)
              tabMap[$li.find('a').attr('href').substring(1)] = $li;
            });

            scope.location = location;
            scope.$watch('location.path()', function(newPath) {
                $tabs.removeClass("active");
                tabMap[newPath].addClass("active");
            });
        }

    };

 }]);

然后在您的 html 中,您只需:

<ul nav-tabs>
  <li><a href="#/One">One</a></li>
  <li><a href="#/Two">Two</a></li>
  <li><a href="#/Three">Three</a></li>
</ul>
<ng:view><!-- Content will appear here --></ng:view>

这是它的插件: http ://plnkr.co/edit/xwGtGqrT7kWoCKnGDHYN?p=preview 。

于 2013-04-16T17:27:41.063 回答
9

您可以非常简单地实现这一点,这是一个示例:

<div ng-controller="MenuCtrl">
  <ul class="menu">
    <li ng-class="menuClass('home')"><a href="#home">Page1</a></li>
    <li ng-class="menuClass('about')"><a href="#about">Page2</a></li>
  </ul>

</div>

你的控制器应该是这样的:

app.controller("MenuCtrl", function($scope, $location) {
  $scope.menuClass = function(page) {
    var current = $location.path().substring(1);
    return page === current ? "active" : "";
  };
});
于 2014-11-11T09:34:12.827 回答
5

将 Angular 版本 6 与 Bootstrap 4.1 一起使用

我能够完成它,如下所示。

在下面的示例中,当 URL 看到“/contact”时,将激活的引导程序添加到 html 标记中。当 URL 发生变化时,它会被删除。

<ul>
<li class="nav-item" routerLink="/contact" routerLinkActive="active">
    <a class="nav-link" href="/contact">Contact</a>
</li>
</ul>

该指令允许您在链接的路由变为活动状态时向元素添加 CSS 类。

在Angular 网站上阅读更多信息

于 2018-09-14T12:56:16.730 回答
5

使用 angular-ui-router 的 ui-sref-active 指令 https://github.com/angular-ui/ui-router/wiki/Quick-Reference#statename

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

于 2016-02-03T07:40:34.307 回答
4

我对位于控制器范围之外的菜单有类似的问题。不确定这是最好的解决方案还是推荐的解决方案,但这对我有用。我已将以下内容添加到我的应用程序配置中:

var app = angular.module('myApp');

app.run(function($rootScope, $location){
  $rootScope.menuActive = function(url, exactMatch){
    if (exactMatch){
      return $location.path() == url;
    }
    else {
      return $location.path().indexOf(url) == 0;
    }
  }
});

然后在视图中我有:

<li><a href="/" ng-class="{true: 'active'}[menuActive('/', true)]">Home</a></li>
<li><a href="/register" ng-class="{true: 'active'}[menuActive('/register')]">
<li>...</li>
于 2013-03-18T15:41:25.247 回答
3

使用指令(因为我们在这里进行 DOM 操作)以下可能是最接近“角度方式”的处理方式:

$scope.timeFilters = [
  {'value':3600,'label':'1 hour'},
  {'value':10800,'label':'3 hours'},
  {'value':21600,'label':'6 hours'},
  {'value':43200,'label':'12 hours'},
  {'value':86400,'label':'24 hours'},
  {'value':604800,'label':'1 week'}
]

angular.module('whatever', []).directive('filter',function(){
return{
    restrict: 'A',
    template: '<li ng-repeat="time in timeFilters" class="filterItem"><a ng-click="changeTimeFilter(time)">{{time.label}}</a></li>',
    link: function linkFn(scope, lElement, attrs){

        var menuContext = attrs.filter;

        scope.changeTimeFilter = function(newTime){
          scope.selectedtimefilter = newTime;

        }

        lElement.bind('click', function(cevent){
            var currentSelection = angular.element(cevent.srcElement).parent();
            var previousSelection = scope[menuContext];

            if(previousSelection !== currentSelection){
                if(previousSelection){
                    angular.element(previousSelection).removeClass('active')
                }
                scope[menuContext] = currentSelection;

                scope.$apply(function(){
                    currentSelection.addClass('active');
                })
            }
        })
    }
}
})

然后您的 HTML 将如下所示:

<ul class="dropdown-menu" filter="times"></ul>
于 2013-04-22T23:22:21.680 回答
2

我对这个问题的解决方案,route.current在角度模板中使用。

由于您有/tasks要在菜单中突出显示的路线,因此您可以将自己的属性添加menuItem到模块声明的路线中:

$routeProvider.
  when('/tasks', {
    menuItem: 'TASKS',
    templateUrl: 'my-templates/tasks.html',
    controller: 'TasksController'
  );

然后在您的模板中tasks.html,您可以使用以下ng-class指令:

<a href="app.html#/tasks" 
    ng-class="{active : route.current.menuItem === 'TASKS'}">Tasks</a>

在我看来,这比所有提议的解决方案都要干净得多。

于 2015-04-07T07:49:16.053 回答
2

我是这样做的:

var myApp = angular.module('myApp', ['ngRoute']);

myApp.directive('trackActive', function($location) {
    function link(scope, element, attrs){
        scope.$watch(function() {
            return $location.path();
        }, function(){
            var links = element.find('a');
            links.removeClass('active');
            angular.forEach(links, function(value){
                var a = angular.element(value);
                if (a.attr('href') == '#' + $location.path() ){
                    a.addClass('active');
                }
            });
        });
    }
    return {link: link};
});

这使您可以在具有 track-active 指令的部分中拥有链接:

<nav track-active>
     <a href="#/">Page 1</a>
     <a href="#/page2">Page 2</a>
     <a href="#/page3">Page 3</a>
</nav>

对我来说,这种方法似乎比其他方法更干净。

另外,如果你使用 jQuery,你可以让它更整洁,因为 jQlite 只有基本的选择器支持。在角度包含之前包含 jquery 的更简洁的版本如下所示:

myApp.directive('trackActive', function($location) {
    function link(scope, element, attrs){
        scope.$watch(function() {
            return $location.path();
        }, function(){
            element.find('a').removeClass('active').find('[href="#'+$location.path()+'"]').addClass('active');
        });
    }
    return {link: link};
});

这是一个jsFiddle

于 2014-01-24T00:09:51.837 回答
1

如果您希望将指令的链接放在包装器中,而不是选择每个单独的链接(更容易查看 Batarang 中的范围),这也很有效:

  angular.module("app").directive("navigation", [
    "$location", function($location) {
      return {
        restrict: 'A',
        scope: {},
        link: function(scope, element) {
          var classSelected, navLinks;

          scope.location = $location;

          classSelected = 'selected';

          navLinks = element.find('a');

          scope.$watch('location.path()', function(newPath) {
            var el;
            el = navLinks.filter('[href="' + newPath + '"]');

            navLinks.not(el).closest('li').removeClass(classSelected);
            return el.closest('li').addClass(classSelected);
          });
        }
      };
    }
  ]);

标记只是:

    <nav role="navigation" data-navigation>
        <ul>
            <li><a href="/messages">Messages</a></li>
            <li><a href="/help">Help</a></li>
            <li><a href="/details">Details</a></li>
        </ul>
    </nav>

我还应该提到我在这个例子中使用了“全脂”jQuery,但是你可以很容易地改变我对过滤等所做的事情。

于 2014-06-04T10:12:55.050 回答
1

这是另一个突出显示活动链接的指令。

主要特征:

  • 适用于包含动态角度表达式的 href
  • 与 hash-bang 导航兼容
  • 与 Bootstrap 兼容,其中活动类应应用于父 li 而不是链接本身
  • 如果任何嵌套路径处于活动状态,则允许使链接处于活动状态
  • 如果链接不活动,则允许禁用链接

代码:

.directive('activeLink', ['$location', 
function($location) {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            var path = attrs.activeLink ? 'activeLink' : 'href';
            var target = angular.isDefined(attrs.activeLinkParent) ? elem.parent() : elem;
            var disabled = angular.isDefined(attrs.activeLinkDisabled) ? true : false;
            var nested = angular.isDefined(attrs.activeLinkNested) ? true : false;

            function inPath(needle, haystack) {
                var current = (haystack == needle);
                if (nested) {
                    current |= (haystack.indexOf(needle + '/') == 0);
                }

                return current;
            }

            function toggleClass(linkPath, locationPath) {
                // remove hash prefix and trailing slashes
                linkPath = linkPath ? linkPath.replace(/^#!/, '').replace(/\/+$/, '') : '';
                locationPath = locationPath.replace(/\/+$/, '');

                if (linkPath && inPath(linkPath, locationPath)) {
                    target.addClass('active');
                    if (disabled) {
                        target.removeClass('disabled');
                    }
                } else {
                    target.removeClass('active');
                    if (disabled) {
                        target.addClass('disabled');
                    }
                }
            }

            // watch if attribute value changes / evaluated
            attrs.$observe(path, function(linkPath) {
                toggleClass(linkPath, $location.path());
            });

            // watch if location changes
            scope.$watch(
                function() {
                    return $location.path(); 
                }, 
                function(newPath) {
                    toggleClass(attrs[path], newPath);
                }
            );
        }
    };
}
]);

用法:

带有角度表达式的简单示例,假设$scope.var = 2 ,如果位置为/url/2,则链接将处于活动状态:

<a href="#!/url/{{var}}" active-link>

引导示例,父 li 将获得活动类:

<li>
    <a href="#!/url" active-link active-link-parent>
</li>

嵌套 url 示例,如果任何嵌套 url 处于活动状态(即/url/1/url/2url/1/2/...) ,则链接将处于活动状态

<a href="#!/url" active-link active-link-nested>

复杂的示例,链接指向一个 url ( /url1 ),但如果选择另一个 ( /url2 ) 则将处于活动状态

<a href="#!/url1" active-link="#!/url2" active-link-nested>

禁用链接的示例,如果它不活动,它将具有“禁用”类:

<a href="#!/url" active-link active-link-disabled>

所有active-link-*属性都可以任意组合使用,因此可以实现非常复杂的条件。

于 2014-04-17T16:05:50.763 回答
1

这是我的两分钱,这很好用。

注意:这与子页面不匹配(这是我需要的)。

看法:

<a ng-class="{active: isCurrentLocation('/my-path')}"  href="/my-path" >
  Some link
</a>

控制器:

// make sure you inject $location as a dependency

$scope.isCurrentLocation = function(path){
    return path === $location.path()
}
于 2015-02-27T13:27:41.017 回答
1

这是我为允许不同级别的路径匹配所做的 kfis 指令的扩展。本质上,我发现需要将 URL 路径匹配到一定深度,因为精确匹配不允许嵌套和默认状态重定向。希望这可以帮助。

    .directive('selectedLink', ['$location', function(location) {
    return {
        restrict: 'A',
        scope:{
            selectedLink : '='
            },
        link: function(scope, element, attrs, controller) {
            var level = scope.selectedLink;
            var path = attrs.href;
            path = path.substring(1); //hack because path does not return including hashbang
            scope.location = location;
            scope.$watch('location.path()', function(newPath) {
                var i=0;
                p = path.split('/');
                n = newPath.split('/');
                for( i ; i < p.length; i++) { 
                    if( p[i] == 'undefined' || n[i] == 'undefined' || (p[i] != n[i]) ) break;
                    }

                if ( (i-1) >= level) {
                    element.addClass("selected");
                    } 
                else {
                    element.removeClass("selected");
                    }
                });
            }

        };
    }]);

这是我使用链接的方式

<nav>
    <a href="#/info/project/list"  selected-link="2">Project</a>
    <a href="#/info/company/list" selected-link="2">Company</a>
    <a href="#/info/person/list"  selected-link="2">Person</a>
</nav>

该指令将匹配指令属性值中指定的深度级别。只是意味着它可以在其他地方多次使用。

于 2013-07-22T13:39:22.720 回答
1

根据@kfis 的回答,它的评论和我的建议,最终指令如下:

.directive('activeLink', ['$location', function (location) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs, controller) {
        var clazz = attrs.activeLink;        
        var path = attrs.href||attrs.ngHref;
        path = path.substring(1); //hack because path does not return including hashbang
        scope.location = location;
        scope.$watch('window.location.href', function () {
          var newPath = (window.location.pathname + window.location.search).substr(1);
          if (path === newPath) {
            element.addClass(clazz);
          } else {
            element.removeClass(clazz);
          }
        });
      }
    };
  }]);

以下是它在 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>

之后使用 css 进行样式设置:

.active { color: red; }
于 2015-10-06T09:31:35.677 回答
1

上述指导性建议对我都没有用。如果您有这样的引导导航栏

<ul class="nav navbar-nav">
    <li><a ng-href="#/">Home</a></li>
    <li><a ng-href="#/about">About</a></li>
  ...
</ul>

(这可能是一个$ yo angular启动)然后你想添加.active <li>元素类列表,而不是元素本身;即<li class="active">..</li>。所以我写了这个:

.directive('setParentActive', ['$location', function($location) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs, controller) {
      var classActive = attrs.setParentActive || 'active',
          path = attrs.ngHref.replace('#', '');
      scope.location = $location;
      scope.$watch('location.path()', function(newPath) {
        if (path == newPath) {
          element.parent().addClass(classActive);
        } else {
          element.parent().removeClass(classActive);
        }
      })
    }
  }
}])

用法set-parent-active.active是默认的所以不需要设置

<li><a ng-href="#/about" set-parent-active>About</a></li>

并且父<li>元素将.active在链接处于活动状态时出现。要使用类似的替代.active.highlight,只需

<li><a ng-href="#/about" set-parent-active="highlight">About</a></li>
于 2016-02-06T19:55:27.260 回答
1

对于那些使用 ui-router 的人,我的回答有点类似于 Ender2050,但我更喜欢通过州名测试来做到这一点:

$scope.isActive = function (stateName) {
  var active = (stateName === $state.current.name);
  return active;
};

对应的 HTML:

<ul class="nav nav-sidebar">
    <li ng-class="{ active: isActive('app.home') }"><a ui-sref="app.home">Dashboard</a></li>
    <li ng-class="{ active: isActive('app.tiles') }"><a ui-sref="app.tiles">Tiles</a></li>
</ul>
于 2016-01-05T06:46:00.680 回答
0

对我来说最重要的是根本不更改引导程序默认代码。这是我的菜单控制器,它搜索菜单选项,然后添加我们想要的行为。

file: header.js
function HeaderCtrl ($scope, $http, $location) {
  $scope.menuLinkList = [];
  defineFunctions($scope);
  addOnClickEventsToMenuOptions($scope, $location);
}

function defineFunctions ($scope) {
  $scope.menuOptionOnClickFunction = function () {
    for ( var index in $scope.menuLinkList) {
      var link = $scope.menuLinkList[index];
      if (this.hash === link.hash) {
        link.parentElement.className = 'active';
      } else {
        link.parentElement.className = '';
      }
    }
  };
}

function addOnClickEventsToMenuOptions ($scope, $location) {
  var liList = angular.element.find('li');
  for ( var index in liList) {
    var liElement = liList[index];
    var link = liElement.firstChild;
    link.onclick = $scope.menuOptionOnClickFunction;
    $scope.menuLinkList.push(link);
    var path = link.hash.replace("#", "");
    if ($location.path() === path) {
      link.parentElement.className = 'active';
    }
  }
}

     <script src="resources/js/app/header.js"></script>
 <div class="navbar navbar-fixed-top" ng:controller="HeaderCtrl">
    <div class="navbar-inner">
      <div class="container-fluid">
        <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
          <span class="icon-bar"></span> <span class="icon-bar"></span> 
<span     class="icon-bar"></span>
        </button>
        <a class="brand" href="#"> <img src="resources/img/fom-logo.png"
          style="width: 80px; height: auto;">
        </a>
        <div class="nav-collapse collapse">
          <ul class="nav">
            <li><a href="#/platforms">PLATFORMS</a></li>
            <li><a href="#/functionaltests">FUNCTIONAL TESTS</a></li>
          </ul> 
        </div>
      </div>
    </div>
  </div>
于 2013-07-19T11:26:43.907 回答
0

有同样的问题。这是我的解决方案

.directive('whenActive',
  [
    '$location',
    ($location)->
      scope: true,
      link: (scope, element, attr)->
        scope.$on '$routeChangeSuccess', 
          () ->
            loc = "#"+$location.path()
            href = element.attr('href')
            state = href.indexOf(loc)
            substate = -1

            if href.length > 3
              substate = loc.indexOf(href)
            if loc.length is 2
              state = -1

            #console.log "Is Loc: "+loc+" in Href: "+href+" = "+state+" and Substate = "+substate

            if state isnt -1 or substate isnt -1
              element.addClass 'selected'
              element.parent().addClass 'current-menu-item'
            else if href is '#' and loc is '#/'
              element.addClass 'selected'
              element.parent().addClass 'current-menu-item'
            else
              element.removeClass 'selected'
              element.parent().removeClass 'current-menu-item'
  ])
于 2013-11-22T20:18:15.860 回答
0
$scope.getClass = function (path) {
return String(($location.absUrl().split('?')[0]).indexOf(path)) > -1 ? 'active' : ''
}


<li class="listing-head" ng-class="getClass('/v/bookings')"><a href="/v/bookings">MY BOOKING</a></li>
<li class="listing-head" ng-class="getClass('/v/fleets')"><a href="/v/fleets">MY FLEET</a></li>
<li class="listing-head" ng-class="getClass('/v/adddriver')"><a href="/v/adddriver">ADD DRIVER</a></li>
<li class="listing-head" ng-class="getClass('/v/bookings')"><a href="/v/invoice">INVOICE</a></li>
<li class="listing-head" ng-class="getClass('/v/profile')"><a href="/v/profile">MY PROFILE</a></li>
<li class="listing-head"><a href="/v/logout">LOG OUT</a></li>
于 2016-08-06T09:00:22.997 回答
0

我刚刚为此写了一个指令。

用法:

<ul class="nav navbar-nav">
  <li active><a href="#/link1">Link 1</a></li>
  <li active><a href="#/link2">Link 2</a></li>
</ul>

执行:

angular.module('appName')
  .directive('active', function ($location, $timeout) {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        // Whenever the user navigates to a different page...
        scope.$on('$routeChangeSuccess', function () {
          // Defer for other directives to load first; this is important
          // so that in case other directives are used that this directive
          // depends on, such as ng-href, the href is evaluated before
          // it's checked here.
          $timeout(function () {
            // Find link inside li element
            var $link = element.children('a').first();

            // Get current location
            var currentPath = $location.path();

            // Get location the link is pointing to
            var linkPath = $link.attr('href').split('#').pop();

            // If they are the same, it means the user is currently
            // on the same page the link would point to, so it should
            // be marked as such
            if (currentPath === linkPath) {
              $(element).addClass('active');
            } else {
              // If they're not the same, a li element that is currently
              // marked as active needs to be "un-marked"
              element.removeClass('active');
            }
          });
        });
      }
    };
  });

测试:

'use strict';

describe('Directive: active', function () {

  // load the directive's module
  beforeEach(module('appName'));

  var element,
      scope,
      location,
      compile,
      rootScope,
      timeout;

  beforeEach(inject(function ($rootScope, $location, $compile, $timeout) {
    scope = $rootScope.$new();
    location = $location;
    compile = $compile;
    rootScope = $rootScope;
    timeout = $timeout;
  }));

  describe('with an active link', function () {
    beforeEach(function () {
      // Trigger location change
      location.path('/foo');
    });

    describe('href', function () {
      beforeEach(function () {
        // Create and compile element with directive; note that the link
        // is the same as the current location after the location change.
        element = angular.element('<li active><a href="#/foo">Foo</a></li>');
        element = compile(element)(scope);

        // Broadcast location change; the directive waits for this signal
        rootScope.$broadcast('$routeChangeSuccess');

        // Flush timeout so we don't have to write asynchronous tests.
        // The directive defers any action using a timeout so that other
        // directives it might depend on, such as ng-href, are evaluated
        // beforehand.
        timeout.flush();
      });

      it('adds the class "active" to the li', function () {
        expect(element.hasClass('active')).toBeTruthy();
      });
    });

    describe('ng-href', function () {
      beforeEach(function () {
        // Create and compile element with directive; note that the link
        // is the same as the current location after the location change;
        // however this time with an ng-href instead of an href.
        element = angular.element('<li active><a ng-href="#/foo">Foo</a></li>');
        element = compile(element)(scope);

        // Broadcast location change; the directive waits for this signal
        rootScope.$broadcast('$routeChangeSuccess');

        // Flush timeout so we don't have to write asynchronous tests.
        // The directive defers any action using a timeout so that other
        // directives it might depend on, such as ng-href, are evaluated
        // beforehand.
        timeout.flush();
      });

      it('also works with ng-href', function () {
        expect(element.hasClass('active')).toBeTruthy();
      });
    });
  });

  describe('with an inactive link', function () {
    beforeEach(function () {
      // Trigger location change
      location.path('/bar');

      // Create and compile element with directive; note that the link
      // is the NOT same as the current location after the location change.
      element = angular.element('<li active><a href="#/foo">Foo</a></li>');
      element = compile(element)(scope);

      // Broadcast location change; the directive waits for this signal
      rootScope.$broadcast('$routeChangeSuccess');

      // Flush timeout so we don't have to write asynchronous tests.
      // The directive defers any action using a timeout so that other
      // directives it might depend on, such as ng-href, are evaluated
      // beforehand.
      timeout.flush();
    });

    it('does not add the class "active" to the li', function () {
      expect(element.hasClass('active')).not.toBeTruthy();
    });
  });

  describe('with a formerly active link', function () {
    beforeEach(function () {
      // Trigger location change
      location.path('/bar');

      // Create and compile element with directive; note that the link
      // is the same as the current location after the location change.
      // Also not that the li element already has the class "active".
      // This is to make sure that a link that is active right now will
      // not be active anymore when the user navigates somewhere else.
      element = angular.element('<li class="active" active><a href="#/foo">Foo</a></li>');
      element = compile(element)(scope);

      // Broadcast location change; the directive waits for this signal
      rootScope.$broadcast('$routeChangeSuccess');

      // Flush timeout so we don't have to write asynchronous tests.
      // The directive defers any action using a timeout so that other
      // directives it might depend on, such as ng-href, are evaluated
      // beforehand.
      timeout.flush();
    });

    it('removes the "active" class from the li', function () {
      expect(element.hasClass('active')).not.toBeTruthy();
    });
  });
});
于 2015-07-08T01:20:16.173 回答
0

我找到了最简单的解决方案。只是为了比较 HTML 中的 indexOf

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 
         $rootScope.isCurrentPath = $location.path();  
    });
});



<li class="{{isCurrentPath.indexOf('help')>-1 ? 'active' : '' }}">
<a href="/#/help/">
          Help
        </a>
</li>
于 2017-04-04T18:10:41.593 回答
0

路线:

$routeProvider.when('/Account/', { templateUrl: '/Home/Account', controller: 'HomeController' });

菜单html:

<li id="liInicio" ng-class="{'active':url=='account'}">

控制器:

angular.module('Home').controller('HomeController', function ($scope, $http, $location) {
    $scope.url = $location.url().replace(/\//g, "").toLowerCase();
...

我在这里发现的问题是菜单项仅在加载整个页面时才处于活动状态。加载局部视图时,菜单不会更改。有人知道为什么会这样吗?

于 2015-09-10T15:46:45.433 回答