How to detect current state within directive

后端 未结 5 2084
臣服心动
臣服心动 2020-12-07 10:36

I\'m using AngularUI\'s routing and I\'d like to do a ng-class=\"{active: current.state}\" but I\'m unsure how to exactly detect the current state in a directiv

相关标签:
5条回答
  • 2020-12-07 11:11

    Also you can use ui-sref-active directive:

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

    Or filters: "stateName" | isState & "stateName" | includedByState

    0 讨论(0)
  • 2020-12-07 11:18

    The use of ui-sref-active directive that worked for me was:

    <li ui-sref-active="{'active': 'admin'}">
        <a ui-sref="admin.users">Administration Panel</a>
    </li>
    

    as found here under the comment labeled "tgrant59 commented on May 31, 2016".

    I am using angular-ui-router v0.3.1.

    0 讨论(0)
  • 2020-12-07 11:20

    If you are using ui-router, try $state.is();

    You can use it like so:

    $state.is('stateName');

    Per the documentation:

    $state.is ... similar to $state.includes, but only checks for the full state name.

    0 讨论(0)
  • 2020-12-07 11:24

    Check out angular-ui, specifically, route checking: http://angular-ui.github.io/ui-utils/

    0 讨论(0)
  • 2020-12-07 11:36

    Update:

    This answer was for a much older release of Ui-Router. For the more recent releases (0.2.5+), please use the helper directive ui-sref-active. Details here.


    Original Answer:

    Include the $state service in your controller. You can assign this service to a property on your scope.

    An example:

    $scope.$state = $state;
    

    Then to get the current state in your templates:

    $state.current.name
    

    To check if a state is current active:

    $state.includes('stateName'); 
    

    This method returns true if the state is included, even if it's part of a nested state. If you were at a nested state, user.details, and you checked for $state.includes('user'), it'd return true.

    In your class example, you'd do something like this:

    ng-class="{active: $state.includes('stateName')}"
    
    0 讨论(0)
提交回复
热议问题