Routing and Views in AngularJS

Routing is another feature in AngularJS, through which we can bind different angular views to their respective controllers. Using views and routing in an application increases the manageability and the user experience.

Routing is taken care by a service provider in AngularJS named as $routeprovider, which is the provider of $route service. This service makes is easier to bind together the Views, controllers and the current browser URL.

So let’s check out how we can use it.

Let’s first create the HTML file and name it anything you wish to.

ng-template helps in defining templates in the application. AngularJS automatically loads the template to the div with ng-view directive (can be seen highlighted in the code snippet below).

Note that we have defined two views, addStudent.htm and viewStudents.htm.

Let’s now write the AngularJS code for the above HTML:

Note that AngularJS provides when… otherwise… statements to deal with the routing feature, where we explicitly specify the individual views and its corresponding controller.

Also, we have defined the respective controllers too.

Running the above code, displays like:

Routing and Views in AngularJS

Click to try out live on jsFiddle

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.