我正在学习角度并尝试创建一个导航栏菜单并设置“活跃”状态'基于当前页面的课程。
<html lang="en" data-ng-app="Afe" class="no-js">
<head>
<!-- code omitted.. -->
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav" data-ng-init="activeMenu='AfeCoverPage'">
<li data-ng-class="{active: activeMenu=='AfeCoverPage'}" data-ng-click="activeMenu='AfeCoverPage'"><a href="#/AfeCoverPage">AFE Cover Page</a></li>
<li data-ng-class="{active: activeMenu=='AfeCostEstimate'}" data-ng-click="activeMenu='AfeCostEstimate'"><a href="#/AfeCostEstimate">AFE Cost Estimate</a></li>
<li data-ng-class="{active: activeMenu=='AfeVariance'}" data-ng-click="activeMenu='AfeVariance'"><a href="#/AfeVariance">AFE Variance</a></li>
</ul>
</div>
</div>
</nav>
<div data-ng-view=""></div>
<!-- code omitted.. -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</body>
</html>
angular.module('Afe', ['ngRoute', 'Afe.controllers']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/AfeCoverPage', { templateUrl: 'partials/AfeCoverPage.html', controller: 'AfeCoverPageCtrl' });
$routeProvider.when('/AfeCostEstimate', { templateUrl: 'partials/AfeCostEstimate.html', controller: 'AfeCostEstimateCtrl' });
$routeProvider.when('/AfeVariance', { templateUrl: 'partials/AfeVariance.html', controller: 'AfeVarianceCtrl' });
$routeProvider.otherwise({ redirectTo: '/AfeCoverPage' });
}]);
angular.module('Afe.controllers', []).
controller('GlobalCtrl', ['$scope', function ($scope) {
}]).
controller('AfeCoverPageCtrl', ['$scope', function ($scope) {
}]).
controller('AfeCostEstimateCtrl', ['$scope', function ($scope) {
}]).
controller('AfeVarianceCtrl', ['$scope', function ($scope) {
}]);
目前它正在运作,当点击Afe封面菜单时,<li>
元素将有效激活&#39;但是我不确定使用ng-click是否正确。代码似乎是重复的。有人能告诉我最好的方法吗?
答案 0 :(得分:3)
你可以使用$ location服务和ng-class
指令中的一个函数,如果它与当前路径匹配,则返回一个bool。
<div class="collapse navbar-collapse" ng-controller="MenuController">
<ul class="nav navbar-nav">
<li data-ng-class="{active: isActive('/AfeCoverPage')}"><a href="#/AfeCoverPage">AFE Cover Page</a></li>
<li data-ng-class="{active: isActive('/AfeCostEstimate')}"><a href="#/AfeCostEstimate">AFE Cost Estimate</a></li>
<li data-ng-class="{active: isActive('/AfeVariance')}"><a href="#/AfeVariance">AFE Variance</a></li>
</ul>
</div>
使用控制器:
.controller('MenuController', function ($scope, $location) {
$scope.isActive = function (path) {
return $location.path() === path;
}
});