AngularJS在为当前页面的链接设置一个活动类方面有任何帮助吗?

我想一定有什么神奇的方法可以做到,但我似乎找不到。

我的菜单是这样的:

 <ul>
   <li><a class="active" href="/tasks">Tasks</a>
   <li><a href="/actions">Tasks</a>
 </ul>

我在我的路由中为它们每个都有控制器:TasksController和ActionsController。

但是我想不出一种方法将a链接上的“活动”类绑定到控制器。

有提示吗?


当前回答

对于那些使用ui-router的人,我的答案有点类似于Ender2050,但我更喜欢通过州名测试来做到这一点:

$scope.isActive = function (stateName) {
  var active = (stateName === $state.current.name);
  return active;
};

相应的HTML:

<ul class="nav nav-sidebar">
    <li ng-class="{ active: isActive('app.home') }"><a ui-sref="app.home">Dashboard</a></li>
    <li ng-class="{ active: isActive('app.tiles') }"><a ui-sref="app.tiles">Tiles</a></li>
</ul>

其他回答

在视图

<a ng-class="getClass('/tasks')" href="/tasks">Tasks</a>

在控制器

$scope.getClass = function (path) {
  return ($location.path().substr(0, path.length) === path) ? 'active' : '';
}

这样,tasks链接将在任何以'/tasks'开头的url中具有活动类。/任务/ 1 /报告)

有一个ng-class指令,它绑定变量和css类。 它还接受对象(className vs bool值对)。

这里有一个例子,http://plnkr.co/edit/SWZAqj

也有同样的问题。以下是我的解决方案:

.directive('whenActive',
  [
    '$location',
    ($location)->
      scope: true,
      link: (scope, element, attr)->
        scope.$on '$routeChangeSuccess', 
          () ->
            loc = "#"+$location.path()
            href = element.attr('href')
            state = href.indexOf(loc)
            substate = -1

            if href.length > 3
              substate = loc.indexOf(href)
            if loc.length is 2
              state = -1

            #console.log "Is Loc: "+loc+" in Href: "+href+" = "+state+" and Substate = "+substate

            if state isnt -1 or substate isnt -1
              element.addClass 'selected'
              element.parent().addClass 'current-menu-item'
            else if href is '#' and loc is '#/'
              element.addClass 'selected'
              element.parent().addClass 'current-menu-item'
            else
              element.removeClass 'selected'
              element.parent().removeClass 'current-menu-item'
  ])

我有类似的问题,菜单位于控制器范围之外。不确定这是最好的解决方案还是推荐的解决方案,但这对我来说是有效的。我已经在我的应用程序配置中添加了以下内容:

var app = angular.module('myApp');

app.run(function($rootScope, $location){
  $rootScope.menuActive = function(url, exactMatch){
    if (exactMatch){
      return $location.path() == url;
    }
    else {
      return $location.path().indexOf(url) == 0;
    }
  }
});

那么在视图中,我有:

<li><a href="/" ng-class="{true: 'active'}[menuActive('/', true)]">Home</a></li>
<li><a href="/register" ng-class="{true: 'active'}[menuActive('/register')]">
<li>...</li>

对于AngularUI路由器用户:

<a ui-sref-active="active" ui-sref="app">

这将在选中的对象上放置一个活动类。