Page navigation bar in Angular.js


In the last post, we have played with grouped checkboxes so let’s learn about angular controllers by writing a simple Page navigation bar we see on every website.

Here is our HTML code for the navigation and I’m using Twitter Bootstrap to make it a bit fancy.


<div class="well sidebar-nav" ng-app="navList">
<ul class="nav nav-list" ng-controller="navCtrl">
<li ng-class="navClass('home')"><a href='#/home'>Home</a></li>
<li ng-class="navClass('about')"><a href='#/about'>About Us</a></li>
<li ng-class="navClass('contact')"><a href='#/contact'>Contact Us</a></li>
</ul>
</div>
‚Äč

We’ve started off by naming our application/module using ng-app directive. This directive designates the root of the application and is typically placed at the root of the page which creates a root scope.

Next, we’ve specified a controller using ng-controller directive which will create a new scope inside the root scope and have a control over the markup inside it. Finally we’ve attached a custom function to set CSS class to each <li> once the URL hash changes after clicking it. ng-class directive comes really handy in such scenarios which takes an expression to evaluate. In our case, we are sending a hash as a parameter to navClass.

Let’s write some Javascript (but nominal) to make it functional.


var navList = angular.module('navList', []);
navList.controller('navCtrl', ['$scope', '$location', function ($scope, $location) {
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'home';
return page === currentRoute ? 'active' : '';
};
}]);

In above code, we’ve defined our module/application named navList and we have a controller and a method navClass inside it. We’re using a special service in angular.js, $location which parses the URL in the browser and makes the URL available in our application. Finally, just match the URL hash with the parameter passed.

Is not that easy and amazing? Check out the Live Demo. Good Night.

If you found this article useful in anyway, feel free to donate me and receive my dilettante painting as a token of appreciation for your donation.
Advertisement