Access $state inside template

不打扰是莪最后的温柔 提交于 2019-12-09 11:03:23

问题


Background

I create an app with a menu on the left which contains several menu items. When the user clicks on an item (or access it via an URL), I want to highlight the item (i.e. apply the class 'active' on the corresponding <li>).

Note : I handle routes with ui.router.

What I tried

Up to now, I try to use a ng-class directive :

<div class="col-sm-3 col-md-2 sidebar">

<ul class="nav nav-sidebar">
  <li ng-class="{active: current=='container.item1'}">
    <a href="#/a/item1">Item 1</a>
  </li>
  <li ng-class="{active: current=='container.item2'}">
    <a href="#/a/item2">Item 2</a>
  </li>
  <li ng-class="{active: current=='container.item3'}">
    <a href="#/a/item3">Item 3</a>
  </li>
</ul>

And on js side :

.controller('container', function($scope, $rootScope, $state) {
  $rootScope.$on('$stateChangeSuccess',
      function(){
        $scope.current = $state.current.name;
      }
  )
})

It works quite good but I wondered if it was possible to reference the state directly in the template, without having to handle manually the event. Something like :

<ul class="nav nav-sidebar">
  <li ng-class="{active: $state.current.name =='container.item1'}">
    <a href="#/a/item1">Item 1</a>
  </li>
  <li ng-class="{active: $state.current.name =='container.item2'}">
    <a href="#/a/item2">Item 2</a>
  </li>

(which does not work)

Any idea?


回答1:


The easy way is to use this:

.run(['$rootScope', '$state', '$stateParams',
  function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
}])

and then anywhere we can access $state and $stateParams, for example like in this template:

<div >
  <h3>current state name: <var>{{$state.current.name}}</var></h3>


  <h5>params</h5>
  <pre>{{$stateParams | json}}</pre>
  <h5>state</h5>
  <pre>{{$state.current | json}}</pre>

</div>

There is an example



来源:https://stackoverflow.com/questions/33020974/access-state-inside-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!