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.