angularjs - 在模板中访问 $state

标签 angularjs angularjs-scope angular-ui-router state

背景

我创建了一个应用程序,左侧有一个菜单,其中包含多个菜单项。当用户单击一个项目(或通过 URL 访问它)时,我想突出显示该项目(即在相应的 <li> 上应用“事件”类)。

注意:我使用 ui.router 处理路由.

我试过的

到目前为止,我尝试使用 ng-class指令:

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

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

它工作得很好,但我想知道是否可以直接在模板中引用状态,而不必手动处理事件。就像是 :
<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>

(这不起作用)

任何的想法?

最佳答案

简单的方法是使用这个:

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

然后在我们可以访问的任何地方 $state$stateParams ,例如在这个模板中:
<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>

an example

关于angularjs - 在模板中访问 $state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33020974/

相关文章:

javascript - 如果所有模型值不为空则显示 Angular

javascript - 如何在 AngularJS 中设置抽象状态作为背景

AngularJS 嵌套指令

javascript - AngularJS 数据与作用域函数的绑定(bind)

javascript - Angular 将参数传递给函数

angularjs - 如何检测 Angular js中多维数组模型的变化

http - AngularJS - 在 http 请求后刷新 View ,$rootScope.apply 返回 $digest 已经在进行中

Angular RouteReuseStrategy 后退按钮/交叉模块

angularjs - $$animateJs 在使用 oclazyload、uigrid 和 nganimate 时不是函数

javascript - 如何在 Angular JS 中使用 ng-model 进行绑定(bind)