I'm new to Angular and still learning. I've created 'header.html' file and include it in my other html files using 'ng-include'. inside my 'header.html', I have a nav bar and I want nav bar links active with the active page. i tried hard and still couldn't get done. much appreciate if someone could help me to figure this out. thanks.
header.html
<body ng-app="headerModule">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup" ng-controller="headerContr">
<div class="navbar-nav">
<a class="nav-item nav-link ng-class:{ active: isActive('/index.html')};" href="./index.html"><span class="fa fa-home fa-lg"></span> Home</span></a>
<a class="nav-item nav-link ng-class:{ active: isActive('/aboutus.html')};" href="./aboutus.html"><span class="fa fa-info fa-lg"></span> About Us</a>
<a class="nav-item nav-link ng-class:{active: isActive('/contactus.html')};" href="./contactus.html"><span class="fa fa-address-book fa-lg"></span> Contact us</a>
</div>
</div>
</nav>
<header class="jumbotron jumbotron-fluid">
<div class="container fluid">
<div class="row">
</div>
</div>
</header>
app.js
var angApp = angular.module('angApp', []);
var headerModule = angular.module('headerModule', []);
headerModule.controller('headerContr', ['$scope', '$location', function($scope, $location){
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
}]);
There are two ways to use
ng-classin the HTML:<p ng-class='{"active" : isActive(params)}'></p><p class='ng-class: isActive(params)'></p>The first evlas the expression and sets the class
activeif true.The second simply takes the returned value of the expression and sets it as a class, so if
isActive()returnesactive, that class would be used.NgClass Documentation
This is a valid method for NgClass. It may be because you have added the
{}into theng-class:definition as well as passing more than an expression.Try removing the
{}from each instance like so and updating theisActivemethod to returnactive(the active class) if true and '' (blank) if false:OTHER OPTION:
I recommend using the
attribute Usageof NgClass. Try to pull it out of theclassattribute and use it as it's own attribute.