提问者:小点点

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


如果我在引导中有一个导航栏

Home | About | Contact

当每个菜单项处于活动状态时,如何为其设置活动类?也就是说,当角度布线处于最佳位置时,如何设置class=“active”

  1. #/for home
  2. #/aboutfor the about page
  3. #/联系人为联系人页面

共3个答案

匿名用户

一种非常优雅的方法是使用ng控制器在ng视图之外运行单个控制器:

<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();
    };
}

匿名用户

我刚刚编写了一个指令来处理这个问题,因此您只需将属性bs active link添加到父级

你可以在这里看到它的作用:http://jsfiddle.net/8mcedv3b/

HTML示例:

<ul class="nav navbar-nav" bs-active-link>
  <li><a href="/home">Home</a></li>
  <li><a href="/contact">Contact</a></li>
</ul>

Javascript:

angular.module('appName')
.directive('bsActiveLink', ['$location', function ($location) {
return {
    restrict: 'A', //use as attribute 
    replace: false,
    link: function (scope, elem) {
        //after the route has changed
        scope.$on("$routeChangeSuccess", function () {
            var hrefs = ['/#' + $location.path(),
                         '#' + $location.path(), //html5: false
                         $location.path()]; //html5: true
            angular.forEach(elem.find('a'), function (a) {
                a = angular.element(a);
                if (-1 !== hrefs.indexOf(a.attr('href'))) {
                    a.parent().addClass('active');
                } else {
                    a.parent().removeClass('active');   
                };
            });     
        });
    }
}
}]);

匿名用户

你可以看看AngularStrap,导航栏指令似乎就是你要找的:

https://github.com/mgcrea/angular-strap/blob/master/src/navbar/navbar.js

.directive('bsNavbar', function($location) {
  'use strict';

  return {
    restrict: 'A',
    link: function postLink(scope, element, attrs, controller) {
      // Watch for the $location
      scope.$watch(function() {
        return $location.path();
      }, function(newValue, oldValue) {

        $('li[data-match-route]', element).each(function(k, li) {
          var $li = angular.element(li),
            // data('match-rout') does not work with dynamic attributes
            pattern = $li.attr('data-match-route'),
            regexp = new RegExp('^' + pattern + '$', ['i']);

          if(regexp.test(newValue)) {
            $li.addClass('active');
          } else {
            $li.removeClass('active');
          }

        });
      });
    }
  };
});

要使用此指令,请执行以下操作:

>

  • 从下载AngularStraphttp://mgcrea.github.io/angular-strap/

    在引导后将脚本包含在页面上。js:

    将指令添加到模块:
    angular。模块('myApp',['$strap.directives'])

    将指令添加到导航栏:

    在每个导航项上添加正则表达式: