Home » AngularJS17 July 2017

AngularJS: Routing & Single Page Application (SPA)

This article shows how you can use routing in AngularJS 1.x and create Single Page Application (SPA).

For routing feature, we need to include angular-route Javascript file and use ngRoute dependency in our AngularJS module. ngRoute module provides the $routeProvider API which has when and otherwise functions used for routing.

Here’s the full source code for our Single Page Application using AngularJS:

Here’s the code for contact.html template file:

As you can see in above code, in when and otherwise functions of $routeProvider, we can use either direct HTML template OR we can define the templateURL. We can also define a controller. We can use the model data of the controller in the templateURL.

For contact page, we have a templateURL named contact.html and a controller named contactCtrl is defined. The contactCtrl controller defines the scope variable named info. This variable value can be used directly in the template file, i.e. contact.html by using double curly brackets.

The other thing to notice is the use of ng-view directive in HTML view. The template or templateURL defined in the routeProvider will be displayed inside ng-view directive. If ng-view is not defined in the HTML elements then the template will not be displayed.

Hope this helps. Thanks.

AngularJS

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed