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

23 浏览
0 Comments

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

如果我在bootstrap中有一个含有以下项的导航栏:

Home | About | Contact

当它们处于活动状态时,如何为每个菜单项设置活动类?也就是说,当angular路由位于以下情况时,如何设置class=\"active\"

  1. 主页使用#/
  2. 关于页面使用#/about
  3. 联系页面使用#/contact
admin 更改状态以发布 2023年5月23日
0
0 Comments

我刚刚写了一个指令来处理这个问题,你只需要在父级

    元素中添加属性bs-active-link,每当路由改变时,它将查找匹配的链接,并将active类添加到相应的

  • 中。

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

    示例 HTML:

    
    

    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');   
                    };
                });     
            });
        }
    }
    }]);
    

0
0 Comments

使用ng-controller来运行一个单一控制器的最优雅的方式是将它放在ng-view之外:\n

    

\n然后在controllers.js中引入:\n

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

0