AngularJS allows us to develop code running on the client that supports routing in a way similar to code running on the server. Using AngularJS support for routing the development of a one page web application becomes much simpler.
The following code sample include a simple HTML file that refers a JavaScript file, where the controllers are created. The simple HTML file includes a div element that functions as a view in which another separated HTML file that functions as a template (out of the four available ones) is injected (in accordance with the defined routing).
The main HTML file includes the div element that functions as a view.
<!doctype html> <html ng-app="project"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular-resource.min.js"> </script> <script src="application.js"></script> </head> <body> <h2>Routing Sample</h2> <div ng-view></div> </body> </html>
The application.js file that includes the definition of the routing and the definition for the four controllers (each controller is associated with a specific template):
angular.module('project',[]). config(function($routeProvider) { $routeProvider. when('/about', {controller:AboutController,templateUrl:'about.html'}). when('/help', {controller:HelpController,templateUrl:'help.html'}). when('/products', {controller:ProductsController,templateUrl:'products.html'}). when('/services', {controller:ServicesController,templateUrl:'services.html'}). otherwise({redirectTo:'/'}); }); function ServicesController() {} function ProductsController() {} function AboutController() {} function HelpController() {}
The about.html template:
some text about the application...
The help.html template:
short help for using the application...
The products.html template:
detailed list of the products...
The services.html template:
detailed list of the services...
The following video clip shows the execution of this code sample, overviews it and explains the way it works.