Angular:如何在点击时切换活动类的导航菜单?

时间:2015-05-15 18:07:49

标签: angularjs

我已经创建了 AngularJS导航菜单,并且我试图突出显示活动菜单项,基于 ng-repeat 即可。

到目前为止,我已将菜单与ng-repeat配合使用,但我不知道要在ng-click函数中放置哪些活动类才能应用。

以下是我所拥有的:

这是我的视图

//View (in jade):
ul(ng-controller='MenuCtrl')
    li(ng-repeat='navLink in navLinks', ng-click='select(navLink)', ng-class='{active: navLink.linkhref == path}')
        a(href='{{navLink.linkhref}}') {{navLink.linktext}}

这是我的控制器

//Controller:
...
  controller('MenuCtrl', function ($scope,$location) {
    $scope.navLinks = [{
        linkhref: '/',
        linktext: 'View Dashboard',
    }, {
        linkhref: '/rpm',
        linktext: 'View RPMs',
    }, {
        linkhref: '/status',
        linktext: 'View Status',
    }, {
        linkhref: '/database',
        linktext: 'View Database',
    }, {
        linkhref: '/config',
        linktext: 'View Configurations',
    }];

    $scope.path = $location.path();

    $scope.select = function(navLink) {
        //idk what to put here to make the "active" class toggle between nav links
        //I could try this: 
        //remove "active" class from nav links
        //then add "active" class to this link
    };
  })
...

这里有一个小提琴和我的代码:

http://jsfiddle.net/bATZ5/1/

到目前为止,行为

  • 当我转到http://localhost / status 时," 查看状态"链接有" 有效"上课。太棒了!
  • 当我点击其他链接时," 查看状态"链接 保持 " 有效",新链接获取"活跃"等级已添加。
  • 基本上点击时没有任何反应,但刷新页面(因为"路径==路径"事情)

资源有用:

1 个答案:

答案 0 :(得分:2)

在您的列表元素上,class FooTest extends TestCase 指令正在将范围< ngClick值与navLink元素的path值进行比较。因此,如果您希望该项目获得该类,只需设置值:

linkhref

虽然这解决了您的问题,但我相信这种菜单方法存在更大的问题。单击链接外部的$scope.select = function(navLink) { $scope.path = navLink.linkhref; } 元素将使该项目显示为活动状态。此外,使用键盘导航(或以任何不触发li的方式)都不会更新菜单。

不是绑定点击,而是可能值得探索一种观察路线的方法:

ngClick

或者我不喜欢的另一种选择:

function updateActiveLink(){
    $scope.path = $location.path();
}
$scope.$on('$routeChangeSuccess', updateActiveLink);