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.
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.
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.
5 thoughts on “Page navigation bar in Angular.js”
thanks. the most simple solution to navbar bootstrap and angularjs seed in 3 hours of googling
The same 🙂
Thanks a lot. It’s working great 🙂 I modified it a bit further to include the nested views as well (the parent remains active). I’ve got one question though. Is it OK for performance? I mean – we call this function a bunch of times everytime we change a page.
Glad to help. I think there will not be any performance problem but you can avoid calling `$location.path().substring(1)` multiple times within the method by setting the current path on $routeChange.