用AngularJS关联路由和导航样式

Relating routing and navigation styles with AngularJS

本文关键字:导航 样式 路由 AngularJS 关联      更新时间:2023-09-26

假设你在Angular中设置了一个基本的路由器,如下所示:

app.config(function($routeProvider) {
    $routeProvider.when('/', {
        redirectTo: "/news"
    }).when('/news', {
        templateUrl: "partials/pages/news.html",
        controller: "NewsCtrl"
    }).when('/about', {
        templateUrl: "partials/pages/about.html",
        controller: "AboutCtrl"
    })
});

然后你有一个index.html看起来像:

<nav>
    <ul>
        <li><a href="#/news" class="active">news</a></li>
        <li><a href="#/about">about</a></li>
    </ul>
</nav>
<section ng-view></section>

在路由对应的链路上添加.active类的最佳方式是什么?为导航创建控制器?使用$rootScope ?等。我对这两个选项都有问题,因为当我实现它时,两者都不太干净。

我使用下一个代码:

<ul class="navigation">
  <li ng-class="{active : (current == '/')}"><a href="/"><span>Articles</span></a></li>
  <li ng-class="{active : (current == '/about')}"><a href="/about"><span>About</span></a></li>
  <li ng-class="{active : (current == '/contact')}"><a href="/contact"><span>Contact</span></a></li>            
</ul> 
在JS:

app.run(['$location', '$rootScope', function($location, $rootScope, $document) {
    $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
        $rootScope.current = $location.path();
    });
}]);