简体   繁体   English

如何使用AngularJS显示导航菜单,该菜单根据正在查看的路线更改“活动”类?

[英]How to show a navigation menu with AngularJS which changes 'active' class depending on which route is being viewed?

I simply want to show a navigation menu like the following in my app: 我只是想在我的应用中显示如下的导航菜单:

<ul>
  <li><a href="#/section1">Section 1</a></li>

  <li class="active"><a href="#/section2">Section 2</a></li>

  <li><a href="#/section3">Section 3</a></li>
</ul>

Here, clicking section 1, section 2, or section 3 will each trigger a route change. 在这里,单击第1部分,第2部分或第3部分将分别触发路径更改。 Currently the <li> for section 2 has the class active which means its the currently active route. 目前,第2节的<li>具有active类,这意味着它是当前活动的路由。 I simply want to move this class around, so eg if Section 3 is clicked, I want the li for section 3 to have the active class. 我只是想移动这个类,所以例如,如果单击第3节,我希望第3节的li具有active类。

What's the best way to achieve this? 实现这一目标的最佳方法是什么?

You could listen to $routeChangeSuccess event (see documentation for $route ) to detect changes. 您可以监听$ routeChangeSuccess事件(请参阅$ route文档)以检测更改。

Reformat your controller and html like this: 重新格式化您的控制器和HTML格式如下:

$scope.navList = [
  { url: '/route1', title: 'Route 1'},
  { url: '/route2', title: 'Route 2'},
  { url: '/route3', title: 'Route 3'}
];

<ul>
  <li ng-repeat="item in navList">
    <a ng-class="{active:item.active}" href="#{{item.url}}">{{item.title}}</a>
  </li>
</ul>

And then listen for changes (in your controller): 然后监听更改(在您的控制器中):

function detectRoute() {
  angular.forEach($scope.navList, function(item) {
    item.active = $location.path().match(new RegExp(item.url)) ? true : false;
  });  
}

$scope.$on('$routeChangeSuccess', detectRoute);

See example in Plunker . 请参阅Plunker中的示例。

I wrapped this up in a module: https://github.com/Espesen/angular-simple-navbar 我把它包装在一个模块中: https//github.com/Espesen/angular-simple-navbar

Controller function: 控制器功能:

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

I achieved this by using bootstrap, it might help you 我通过使用bootstrap实现了这一点,它可能对你有帮助

$('ul.nav > li').click(function (e) {
        e.preventDefault();
        $('ul.nav > li').removeClass('active');
        $(this).addClass('active');                
    });

The working fiddle is here 工作小提琴在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM