AngularJS로 활성 탭 스타일 설정


144

AngularJS에 다음과 같이 설정된 경로가 있습니다.

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

상단 막대에 탭 스타일의 링크가 있습니다. 현재 템플릿 또는 url에 따라 탭에 'active'클래스를 추가하려면 어떻게합니까?



4
@AminMeyghani이 질문은 거의 1 년 후에 질문 된 질문과 어떻게 중복 될 수 있습니까?
— Regent

답변:


274

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>

3
이것은 / foo / : bar와 같은 동적 URL을 지원하기 때문에 지금까지 본 최고의 솔루션입니다.
— martinpaulucci

3
실제로이 작업을 수행 할 수 없었습니다. plnkr을 제공 할 수 있습니까?
— PPPaul

9
한 가지 : $scope.activeTab = $route.current.activetabHTML을 좀 더 깔끔하게 유지할 수 있도록 설정 하는 것이 좋습니다.
— Christoph

2
AngularJS 1.0.8에서는 작동하지 않습니다. $ route.current는 정의되어 있지 않습니다.
— 메기

2
$rootScope아래 의 @Lucas 트릭 과 결합 하여 모든 범위에서 사용할 수 있습니다.
— colllin

134

이를 수행하는 한 가지 방법은 ngClass 지시문과 $ location 서비스를 사용하는 것입니다. 템플릿에서 다음을 수행 할 수 있습니다.

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

여기서 isActive다음과 같이 정의 된 범위에서 함수가 될 것이다 :

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')}"각 탐색 탭에서 반복 하는 것은 지루할 수 있으므로 (많은 탭이있는 경우)이 논리는 매우 간단한 지시문의 후보가 될 수 있습니다.


1
'매우 간단한 지시문'이 실제로 작성하기가 매우 간단하다는 것을 알기까지 오랜 시간이 걸렸습니다. 그래서 아래에 하나를 제공했습니다. :-) 선언적이지 않은 구성없이 다양한 상황에서 재사용 할 수 있어야합니다.
— XML

1
jsFiddle을 보면 페이지로드시 현재 페이지를 어떻게 활성화합니까? 이 예제는 사용자가 옵션을 클릭 할 때만 작동합니다. 예를 들어 외부 링크에서 홈페이지에 방문 할 때 '홈'탐색 메뉴를 강조 표시 할 수 있습니다.
— thathurtabit

Ahh는 이것에 대해 약간 내 머리를 긁고있었습니다. 감사!
— masterwok

41

사용자 정의 지시어를 사용하는 파벨의 조언에 따라, 여기의 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"인 경우 location.path ()가 "# / home"과 일치합니다.href . 경로의 두 번째 레벨 또는 세 번째 또는 11 번째에 반응해야하는 탭이있는 경우 그에 따라 조정하십시오. 1 이상의 슬라이싱은 href 0에서 악의적 인 '#'을 무시하고 인덱스 0에 있습니다.

<a>요소가 href현재 경로와 비교할 속성 의 존재를 가정하고 있기 때문에 유일한 요구 사항은에 대해 호출 하는 것입니다. 그러나 <li>또는 무언가 를 호출하는 것을 선호하는 경우 부모 또는 자식 요소를 읽거나 쓰는 데 상당히 쉽게 적응할 수 있습니다 . 단순히 pathLevel 인수를 변경하여 여러 컨텍스트에서 재사용 할 수 있기 때문에 이것을 파헤칩니다. 읽을 깊이가 논리에서 가정 된 경우 탐색의 여러 부분에 사용할 여러 버전의 지시문이 필요합니다.


편집 3/18/14 : 솔루션이 잘못 일반화되었으며 반환 된 'activeTab'값에 대한 인수를 정의하면 활성화됩니다 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>

이 버전은 더 이상 원격으로 부트 스트랩 스타일 HTML과 유사하지 않습니다. 그러나 더 현대적이고 더 적은 수의 요소를 사용하므로 부분적으로 사용합니다. 이 버전의 지시문과 원본은 이제 Github 에서 드롭 인 모듈로 사용할 수 있으며 종속성으로 선언 할 수 있습니다. 누군가가 실제로 사용한다면 Bower-ize에 기뻐할 것입니다.

또한의 부트 스트랩 호환 버전을 원한다면 angular-ui-bootstrap Tabs 모듈<li> 을 사용할 수 있습니다 .angular-ui-bootstrap 탭 모듈 은 원래 게시물 이후에 나온 것으로 생각되며 아마도이 게시물보다 훨씬 선언적입니다. 기본 사항은 덜 간결하지만 비활성화 된 탭 및 활성화 및 비활성화시 발생하는 선언적 이벤트와 같은 몇 가지 추가 옵션을 제공합니다.


4
나는 아무도 이것에 실제로 투표를한다고 믿을 수 없었다! 여기 내 2 센트입니다. 코드에는 작은 실수가 있지만 'tabLevel'은 'activeTab'으로 생각됩니다. Bootstrap 스타일의 경우 A 요소 대신 LI 요소에 'active'클래스를 추가 할 수 있습니다. 그러나 이것은 약간의 변경 만 필요합니다.
— David Lin

1
당신은 activeTab, @DavidLin에 대해 절대적으로 맞습니다. 편집했습니다. 그러나 나는 Bootstrap의 구조를 좋아하지 않으므로 의도적 인 차이가 있습니다. 사실, 탐색 추상화는에 속하지 않을 수도 ul있고 아마도 nav다른 그룹화 요소로 감싸 진 앵커 모음 일뿐 이라고 생각하기 시작 했습니다 . 의 중개 계층을 다루는 것은 li보상없이 복잡성을 더하는 것입니다. 특히 현재 nav진행중인 상황을 명확하게하기 위해 우리가 사용할 수있는 요소가 있기 때문입니다.
— XML

이것은 간단하고 훌륭합니다. 나는 Angular에 이미있는 경로를 확인하기 위해 이와 같은 것이 없다는 것에 놀랐습니다.
— Intellix

1
bootstrap3과 함께 작동하게하려면`element.addClass ( "active");`를`element.parent ( 'li'). addClass ( "active");`로 변경하기 만하면됩니다. 명명 된 , 탭이 활성화되어있는 것처럼 보이는 활성 탭의 is-active-tab insead 와 같은 것이 있습니다. 그렇지 않으면 이것은 매우 좋은 지시어입니다. @domi으로 대답이 변경 참조
— boatcoder

이 페이지의 가장 좋은 해결책은 공감 률이 거의 없다는 것을 믿을 수 없습니다.
— Karolis

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>

이 수정에 감사드립니다. 아주 좋아요 페이지가 처음로드 될 때 활성 탭을 설정하기위한 제안 사항이 있습니까?
— Hairgami_Master

2
당신이 원하는 것에 달려 있습니다. 일반적으로 '/'url을 주 컨트롤러로 사용합니다. 이렇게하면 사용자가 URL을 방문 할 때 해당 컨트롤러를로드하고 해당 탭을 활성으로 설정합니다. 위의 예에서는 '/'url이 없으므로 해당 경우 .otherwise () $ routeProvider를 추가하십시오. when ( '/ dashboard', {templateUrl : 'partials / dashboard.html', 컨트롤러 : Ctrl1}). when ( '/ lab', {templateUrl : 'partials / lab.html', 컨트롤러 : Ctrl2}). otherwise ({redirectTo : '/ dashboard'}); 행운을 빕니다!
— Lucas

@Lucas에게 감사드립니다. 도움이되었습니다. 어떤 이유로 나는 주 경로에 # 기호를 추가해야했습니다. when ( '# /', {controller : FormsController, templateUrl : 'partials / dashboard.html'}).
— Hairgami_Master

나는이 방법을 선호합니다. rootScope를 가지고 어디에서든 무엇이든 할 수 있습니다
— wrivas at

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

    };

}]);

1
href에 docs.angularjs.org/guide/directive#Attributes 표현식이 포함 된 경우 $ observe를 사용해야 합니다. : 업데이트 바이올린 참조 jsfiddle.net/p3ZMR/10
— Narretz

14

가장 간단한 해결책은 다음과 같습니다.

Angular JS로 부트 스트랩 navbar 활성 클래스를 설정하는 방법은 무엇입니까?

어느 것이 :

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

2
가장 쉬운 것에 동의
— AngeloS

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>

읽을만한 가치가 있습니다.


4

다음은 경로 수준 대신 검색 문자열을 사용하는 domi의 LI 변경이 포함 된 다른 XMLillies 버전입니다. 내 유스 케이스에서 일어나는 일이 조금 더 분명하다고 생각합니다.

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>

3

나는 XMLilley의 답변이 가장 적응력이 뛰어나고 방해가되지 않는 것으로 나타났습니다.

그러나 나는 작은 결함이 있었다.

부트 스트랩 nav와 함께 사용하려면 다음을 수정하십시오.

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>

nvm, 이것이 내 잘못이라고 두 번 불렸다. "if (attrs.href! = undefined)"가 필요하지 않은 것 같습니다.
— domi

3

부트 스트랩 예.

라우팅 (ngview)에 내장 된 Angular를 사용하는 경우이 지시문을 사용할 수 있습니다.

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>

속성에서 원하는 클래스 이름을 설정할 수 있기 때문에 이렇게하는 것이 좋습니다.


2

또한 간단하게 할 수 있습니다 범위로 위치를 주입 탐색의 스타일을 공제하는 것을 사용 :

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

그런 다음에 사용하십시오 ng-class:

<li ng-class="{active: location.path() == '/search'}">
  <a href="/search">Search><a/>
</li>

마크 업에서 $ root.location.path ()가 아니어야합니까?
— Irshu

@ Irshu : 아마도 더 깨끗할 수는 있지만 위의 접근법은 저에게도 효과적이었습니다.
— Der Hochstapler

2

다른 방법은 ui-sref-active 를 사용하는 것입니다

ui-sref와 ​​함께 작동하여 관련 ui-sref 지시문의 상태가 활성 일 때 요소에 클래스를 추가하고 비활성 상태 일 때이를 제거합니다. 주요 사용 사례는 "active"상태의 메뉴 버튼이 비활성 메뉴 항목과 구별되도록 다르게 표시하여 ui-sref에 의존하는 탐색 메뉴의 특수 모양을 단순화하는 것입니다.

용법:

ui-sref-active = 'class1 class2 class3'-클래스 "class1", "class2"및 "class3"은 각각 관련 ui-sref의 상태가 활성화 될 때 지시문 요소에 추가되고 비활성화되면 제거됩니다.

예 :
다음 템플릿이 주어지면

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

앱 상태가 "app.user"이고 값이 "bilbobaggins"인 상태 매개 변수 "user"를 포함하면 결과 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>

감사. 이온 프레임 워크에서 작업 할 때 정말 유용합니다!
— Avijit Gupta

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/


링크 목록에 대한 데이터 중심 접근 방식이 마음에 듭니다. 그리고 일부는 링크 배열을 서비스 / 공장으로 옮길 수도 있습니다.
— 그랜트 린지

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>

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에 의존하지 않으므로 하위 페이지 등에 쉽게 설정할 수 있습니다.


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

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>또는 <a>태그 에 활성 클래스를 추가하기 만하면 됩니다. 처럼,

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

즉, 사용자가 정보 페이지를 클릭 할 때마다 현재 탭을 자동으로 식별하여 활성 CSS 클래스를 적용합니다.

이게 도움이 되길 바란다!


-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>
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.