Angular UI 라우터 : 중첩보기로 탐색 할 때 부모 뷰를 "활성"으로 가져 오는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com//questions/22054391

문제

UI 라우터를 구현 한 프로젝트에서 작업하고 있으며 ui-sref-active="active"를 사용하여 해당 항목이 현재 경로 인 경우 탐색 메뉴 항목에 활성 클래스를 추가합니다.그러나 해당보기에서 중첩 된보기로 이동하면 상위 메뉴 항목이 더 이상 활성화되지 않습니다.다음 Plunker를 참조하십시오 :

http://plnkr.co/edit/2coeds?p=preview <./ P>

기본적으로 (또는 클릭하면) Route 1은 "Active"입니다."목록보기"를 클릭하면 경로 1이 더 이상 작동하지 않습니다.

편집 :

이 예제와 실제 프로젝트의 유일한 차이점은 실제 프로젝트의 탐색 메뉴가 자체 컨트롤러를 가지고 있으므로 "Route1"의 컨트롤러와 동일한 범위를 사용하지 않는다는 것입니다.

도움이 되었습니까?

해결책

업데이트 된 UI-Router 0.2.13의 편집 :

ui-sref-active="active"는 현재 현재 상태가 UI-SREF의 상태 또는 모든 어린이

에있을 때 '활성'클래스를 설정합니다.

ui-sref-active-eq="active"는 ui-sref-active의 이전 반복으로 작동하며 정확한 상태의 클래스 만 설정합니다

원래 답변 :

열기 UI-Router 문제를 참조하십시오. https://github.com/angular-ui/ui-router/issues/704 818

일반적인 해결 방법 사람이 제안됩니다 :

ng-class="{active:$state.includes('route1')}"
.

물론 $ State는 $ Scope에 추가해야합니다.업데이트 된 Plunk : http://plnkr.co/edit/khldjp?p=preview

다른 팁

ui-sref-active="active"

에 대한 잘못된 이해가 잘못되었습니다.
<li ui-sref-active="active"><a ui-sref="route1">Route 1</a></li>
.

상태 Route1에있을 때만 특별한 CSS를 보여줍니다 (참조 https://github.com/angular-ui/ui-router/wiki/quick-reference#wiki-ui-sref-siactive ). 라우트 1을 클릭 할 때의 경우가 있지만 "목록보기"를 클릭하면 더 이상 Route1이 아닙니다. 오히려 당신은 주 "route1.list"에 있습니다. 다음 코드를 작성 하여이 문제를 확인할 수 있습니다. 이것은 주정부가 어떻게 작동하는지 이해하기위한 것입니다.

js

내부 컨트롤러

$rootScope.currentState = $state.$current.name //using rootScope so that you can access the variable anywhere inside html
.

html 내부

{{currentState}}
.

UI-SREF 활성의 설명서를 자세히 살펴보면 StateName뿐만 아니라 StateParams뿐만 아니라 STEAPARAMS도 더 이상 CSS를 변경하지 않습니다. SourceCode에서 더 명확 해집니다.

 function update() {
        if ($state.$current.self === state && matchesParams()) {
          $element.addClass(activeClass);
        } else {
          $element.removeClass(activeClass);
        }// route1===route1.list will not be true.
.

문제를 해결하려면 범위 변수가 중첩 된 뷰에서 상속됩니다.

경로 제어기 내부.

$scope.route1Active = true;
.

html

<li ng-class={active:route1Active}><a ui-sref="route1">Route 1</a></li>
.

Angular UI 라우터는 이제 기본적 으로이 기능을 지원합니다. https://github.com/angular-ui/ui-router/commit./ bf163ad6ce176ce28792696C8302D7CDF5C05A01

내 해당 솔루션이 설정되어야했습니다 :

<li ng-class="{ 'active': state.current.name.indexOf('route1') != -1 }">
.

상태는 이전에 컨트롤러의 범위에 추가되었습니다.

$scope.state = $state;
.

컨트롤러에서 어떤 일을 할 필요가 없습니다.다음은 예제 코드입니다.

    <ul class="nav nav-pills nav-stacked" role="tablist">
        <li ui-sref-active="active"><a ui-sref="Booking.Step1" href="#/Booking/Step1">Step1</a></li>
        <li ui-sref-active="active"><a ui-sref="Booking.Step2" href="#/Booking/Step2" >Step2</a></li>
        <li ui-sref-active="active"><a ui-sref="Booking.Step3" href="#/Booking/Step3">Step3</a></li>
        <li ui-sref-active="active"><a ui-sref="Booking.Step4" href="#/Booking/Step4">Step4</a></li>
        <li ui-sref-active="active"><a ui-sref="Booking.Step5" href="#/Booking/Step5">Step5</a></li>
    </ul>
.

경로 구성 :

$stateProvider.state('Booking', {
        abstract: true,
        url: '/Booking',
        templateUrl: "TourApp/Templates/Booking/SideMenu.html",
        controller: "SideMenuController"
    });

    $stateProvider.state('Booking.Step1', {
        url: "/Step1",
        views: {
            'content': {
                templateUrl: "TourApp/Templates/Booking/Step1.html",
                controller: "Step1Controller"
            }
        }
    });

    $stateProvider.state('Booking.Step2', {
        url: "/Step2",
        views: {
            'content': {
                templateUrl: "TourApp/Templates/Booking/Step2.html",
                controller: "Step2Controller"
            }
        }
    });
.

이제 그들은 업데이트되었고 새로운 방법은

입니다.
 <a ui-sref-active="{'active': 'main.app.manage.**'}" ui-sref="main.app.manage.people.list"></a>
.

아래의 상태 파일은

 angular.module('manage.people', ['people.invite'])
  .config(['$stateProvider', function($stateProvider) {
    $stateProvider
      .state('main.app.manage.people', {
        url: '/people',
        abstract: true,
        cache: false,
        views: {
          'tabContent': {
            template: '<div ui-view="peopleContent"></div>',
            controller: 'peopleController'
          }
        }
      })
      .state('main.app.manage.people.list', {
        url: '/list',
        views: {
          'peopleContent': {
            templateUrl: '/internal/main/app/manage/people/views/people.html',
            controller: 'peopleListController'
          }
        }
      });
.

우리는 이미 "해킹" / P>

그것은 할 수있는 방법 :

html>

 <li ui-sref-active="active" >
   <a href="#" class="submenu" ui-sref="bands">
       <i class="fa fa-location-arrow" aria-hidden="true"></i>
                     Bands
           <span class="fa fa-chevron-down"></span>
   </a>

   <ul class="nav child_menu">
        <li ui-sref-active="active">
            <a  ui-sref="bands.nirvana">
                 Nirvana   
            </a>
       </li>
       <li ui-sref-active="active">
            <a  ui-sref="bands.iron">
                Iron
            </a>
       </li>
       <li ui-sref-active="active">
            <a  ui-sref="bands.metalica">
                Metalica
            </a>
       </li>           
  </ul>
.

우리의 라우터 구성은 다음과 같습니다>

$stateProvider.state('bands', {
    abstract: true,
    url: '/bands',
    templateUrl: "myapp/categories/template.bands.html", //<ui-view></ui-view> 
    controller: "SomeController as vm"
}).state('bands.nirvana', {
    url: '/nirvana',
    templateUrl: "myapp/categories/band.nirvana.html",
    controller: "SomeController as vm"
}).state('bands.iron', {
    url: '/iron',
    templateUrl: "myapp/categories/band.iron.html",
    controller: "SomeController as vm"
}).state('bands.meatlica', {
    url: '/metalica',
    templateUrl: "myapp/categories/band.metalica.html",
    controller: "SomeController as vm"
})
.

여기에 2 년 후에 질문이 묻지 않았지만 angular-ui-router는이 문제를 해결하는 데 훨씬 능숙한 접근법을 가지고 있습니다.중첩 상태도 작동했습니다.

<ul>
  <li ui-sref-active="active" class="item">
    <a ui-sref="home">Home</a>
  </li>
  <!-- ... -->
</ul>
.

앱이 home 상태로 탐색 할 때 이는 HTML이 어떻게 표시되는지입니다.

<ul>
  <li ui-sref-active="active" class="item active">
    <a ui-sref="home">Home</a>
  </li>
  <!-- ... -->
</ul>
.

ui-sref-active 빠른 참조 :

ui-sref와 함께 지침 작업을 수행하여 요소에 클래스를 추가합니다. 관련 UI-Sref 지시문의 상태가 활성화되고 제거 될 때 그것이 비활성 상태 일 때.기본 사용 사례는 그를 단순화하는 것입니다 탐색 메뉴의 특별한 외관은 UI-Sref에 의존하여 "활성"상태의 메뉴 버튼이 다른 것처럼 보이고 구별됩니다. 비활성 메뉴 항목에서

완전한 문서. / P>

이것이 당신이 찾고있는 것입니다. 목록 클래스의 상위 URL을 마치면, 하위 클래스 상위 클래스로 이동할 때마다 활성화됩니다

1 단계 : NAV 바에 대한 컨트롤러 추가 NAV 바가 포함 된 기존 컨트롤러에있는 기존 컨트롤러가 다음을 추가합니다.

app.controller('navCtrl', ['$scope', '$location', function($scope, $location) {
        $scope.isActive = function(destination) {
        return destination === $location.path();
    }

}]);
.

step2 : NAV 바에서

<li ng-class="{active: isActive('/home')}"><a ui-sref="app.home">Browse Journal</a></li>
.

.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top