AngularJS 导航栏动态添加.active

在传统jQuery中,实现导航栏动态添加.active类的思路比较简单,就是当点击的时候,清除其他.active,然后给当前类加上.active。

但是在AngularJS中,就不能再采用这种jQuery思维来实现了。

思路如下:

  1、定义items,存储导航栏的内容

  2、在html中,用ng-repeat 指令去变量items,输出导航栏的内容

  3、用ng-class{'active', isActive(item.href)} 指令去判断当前的url与item.href是否相等,相等则加上.active

  4、在controller的函数中 isActive(href)去判断,如果二者相等返回true

JS代码

 1 .controller('HeaderCtrl', ['$scope','$location', function ($scope,$location) {
 2         $scope.items = [{
 3             id: '1', name: '首页', href: '#/'
 4         },{
 5             id: '2', name: '活期', href: '#/product/tmb'
 6         },{
 7             id: '3', name: '定期', href: '#/product/dcb'
 8         },{
 9             id: '4', name: '添牛', href: '#/product/tnb'
10         },{
11             id: '5', name: '安全', href: '#/security'
12         },{
13             id: '6', name: '账户', href: '#/profile'
14         }]
15 
16         $scope.selected = 1;
17         $scope.isActive = function (current) {
18             var href = '#'+$location.url();
19             return current === href;
20         }
21     }])

HTML代码

<ul id="nav1" class="nav nav-pills" role="tablist">
                <li role="presentation" ng-repeat="item in items">
                    <div class="header_home" ng-class="{'active':isActive(item.href)}">
                        <a ng-href="{{item.href}}" ><span class="h4">{{item.name}}</span></a>
                    </div>
                </li>
</ul>
原文地址:https://www.cnblogs.com/superman66/p/4840751.html