LxD Series: Implementing AngularJS templates and routers

Ok so we are going to implement templates and routers in AngularJS. Routers are going to help us to get unique URLs per page, or view while templates, as you know will help to provide theme of our app.

NgAddressBook

This is what we came up in my last post. What I am going to do to shift the markup of this listing in a separate file and come up with a layout. Therefore index.html will look like this:

You should notice that I removed all the stuff from content div and add another directive, ng-view. Ng-view tells AngularJS that particular DIV will be used as a container of multiple views. Now I create a folder named views and a file in it with name list.html

Now this thing need to be accessed via URL and for that routers need to be defined. In main.js routers will be set like this:

In above code main route has been set by configuring $routeProvider  which takes two parameters; first takes pattern of matched path, in our case it’s ‘/’ while second parameter takes an object having properties templateUrl and controller.

Basically, the code above tells AngularJS that when someone main URL(‘/’) it should execute the controller ngAddressListController and pass on the data from controller to template list.html. Result will be same as given on above screen. Let’s a couple of screens further in the app. One to add record and other to show details of individual record.

 

 

Javascript will now look like this:

I added two more routers; /add and /details:id . You should notice that I created a separate controller, ngAddressDetailsController in which I accessed queryString parameter by passing $routeParams which holds info of all parameters passed via when() method. In detail view you can access it by calling $scope object.

I have left the implementation of detail View. It should not be difficult if you follow what I mentioned in this post.

That’s all folks. Next post will be the last post in AngularJS series in which I will cover to $http object for AJAX purpose.

You can get the latest code of this post from Github.
As always, give your feedback and find mistakes in the posts to make them better.

 

Join with me and let’s learn together!

* indicates required


Leave a Reply

Your email address will not be published. Required fields are marked *