programing

앵글을 사용하여 활성 탭 스타일 설정JS

randomtip 2023. 3. 12. 21:09
반응형

앵글을 사용하여 활성 탭 스타일 설정JS

Angular에 설정된 경로가 있습니다.JS는 다음과 같습니다.

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

상단 표시줄에 탭으로 표시된 링크가 있습니다.현재 템플릿 또는 URL에 따라 탭에 '액티브' 클래스를 추가하려면 어떻게 해야 합니까?

이 할 수 있는 은 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>

이를 위한 한 가지 방법은 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')}"각 네비게이션 탭에 있는 것은 지루할 수 있기 때문에(탭이 많은 경우), 이 논리는 매우 단순한 지시의 후보가 될 수 있습니다.

디렉티브를 Pavel의할 수 에 나타냅니다.이 버전은 "Pavel" "Pavel" "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

declaration합니다.중 $location.path()와 합니다.href으로로돌돌돌

<li class="nav_tab"><a href="#/home" detect-active-tab="1">HOME</a></li>

따라서 탭이 경로의 기본 수준에 반응해야 하는 경우 '1' 인수를 사용합니다.location인 "location.path()" "/home" 의 home" 에 "#/와됩니다.href패스의 두 번째 레벨, 세 번째 레벨 또는 11번째 레벨에 반응하는 탭이 있는 경우는, 적절히 조정합니다. 1 이상의 의 neficious '#'은 01에 .

은 IOS에서 입니다.<a>'일부러'가 하고 있기 href현재 경로와 비교합니다. 부모 요소를는, ,, 쓰, 쓰, 쓰, 쓰, 쓰, 쓰, 쓰, 쓰, 쓰, 쓰, 쓰, the, 쓰, 쓰, 쓰, the, the, the, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,,<li>pathLevel인수만으로 많은 할 수 있기 기능을 사용할 수 있습니다.로직에서 읽을 수 있는 깊이를 가정한 경우 탐색의 여러 부분에서 사용하려면 여러 버전의 지시문이 필요합니다.


32014 3 18 :하여 activeTab'하면 활성화 . 액티브 탭 arg입니다.undefined$location.path()및의 , 「 。hrefundefined === 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>

이 버전은 더 이상 Bootstrap 스타일의 HTML과 전혀 유사하지 않습니다. 하지만 더 현대적이고 적은 수의 요소를 사용하기 때문에 저는 이 버전이 마음에 듭니다.이 버전의 디렉티브와 원본은 이제 Github에서 의존관계로 선언할 수 있는 드롭인 모듈로 사용할 수 있습니다.누가 실제로 사용한다면 기꺼이 바우어라이즈를 하겠습니다.

「」를 한 부트 로 하는 .<li>님은 angular-ui-bootstrap Tabs 모듈을 이용하실 수 있습니다.이 모듈은 원래 투고 이후에 나온 것으로, 아마도 이것보다 더 선언적인 것으로 생각됩니다.기본 정보에는 덜 간결하지만 활성화 및 비활성화 시 실행되는 비활성 탭 및 선언 이벤트와 같은 몇 가지 추가 옵션을 제공합니다.

@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>

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

    };

}]);

가장 심플한 솔루션:

Angular JS를 사용하여 부트스트랩 네비게이션바의 액티브클래스를 설정하려면 어떻게 해야 하나요?

즉, 다음과 같습니다.

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.controllers에 포함:

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

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>

읽을 가치가 있다.

경로 수준 대신 검색 문자열을 사용하는 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>

XMLilley의 anwser가 가장 우수하고 적응력이 뛰어나며 간섭이 없다는 것을 알았습니다.

하지만 작은 결함이 있었다.

부트스트랩 내비게이션을 사용하기 위해 수정한 방법은 다음과 같습니다.

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!)를 추가했습니다.이 함수는 견습적으로 두 번 호출되며, 두 번째 오류 발생이기 때문에 =기호)"라고 합니다.

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>

부트스트랩 예시

Angules built in routing(ngview)을 사용하는 경우 다음 명령을 사용할 수 있습니다.

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>

속성으로 원하는 클래스 이름을 설정할 수 있기 때문에 이 작업이 마음에 듭니다.

또한 스코프에 위치를 삽입하고 이를 사용하여 탐색 스타일을 제외할 수도 있습니다.

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

그, 이에서 하세요.ng-class:

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

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

ui-sref와 함께 작동하여 관련된 ui-sref 지시문의 상태가 활성화되어 있을 때 요소에 클래스를 추가하고 비활성 상태일 때 해당 요소를 제거합니다.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>

클래스 이름은 디렉티브링크 시간 동안 한 번 보간됩니다(보간된 값에 대한 추가 변경은 무시됩니다).공백으로 구분된 형식으로 여러 클래스를 지정할 수 있습니다.

옵션을 $state.go()에 전달하려면 ui-sref-opts 디렉티브를 사용합니다.예를 들어:

<a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>

컨트롤러에 커스텀 속성이 있다는 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.disples

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/

'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>

일부 페이지에서는 템플릿만 렌더링하고 컨트롤러는 전혀 없기 때문에 컨트롤러를 변경할 필요가 없는 솔루션이 필요했습니다.이 사용하자고 .$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에 의존하지 않기 때문에, 서브 페이지등의 설정이 매우 간단합니다.

어디서 이 방법을 찾았는지 기억이 나지 않지만, 꽤 간단하고 잘 작동합니다.

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

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

active .<li> ★★★★★★★★★★★★★★★★★」<a> 꼬리표, 꼬리표 ★★★★★★★★★★★★★★★★★,

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

즉, 사용자가 About 페이지를 클릭할 때마다 현재 탭이 자동으로 식별되어 활성 css 클래스가 적용됩니다.

도움이 됐으면 좋겠네요!

해결을 위해 이곳에 왔다.위의 솔루션은 정상적으로 동작하고 있습니다만, 조금 복잡할 필요는 없습니다.여전히 쉽고 깔끔한 해결책을 찾고 있는 사람들을 위해, 그것은 완벽하게 일을 해낼 것입니다.

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

언급URL : https://stackoverflow.com/questions/12295983/set-active-tab-style-with-angularjs

반응형