Navigation is one of the most important aspects of any web application.Navigation means loading different UI based on user input and selection.Routing in AngularJS means selecting different views depending on the browser URL.
Application consists of different UI elements defined in different views.To change the view displayed to the user routing is used.Routing in AngularJS simplifies the process of defining the URL structure and mapping URLs to the views.
AngularJS handles routing using ngRoute module.To implement routing in AngularJS application follow the below steps:
1. create AngularJS module
Pass ngRoute as second parameter.This specifies dependency on ngRoute module.AngularJS automatically injects ngRoute object when we create the module as below:
var app = angular.module("myApp", ["ngRoute"]);
2.call the config method
This function is used to configure the module.In the function parameter we specify $routeProvider as a parameter.AngularJS automatically creates $routeProvider object.
app.config(function($routeProvider) { });
3.Define routes: We define routes using the when function of the $routeProvider object.$routeProvider provides when method which is used to configure routes.Two parameters needs to be passed to when method.The first is the URL pattern.Second is the object which defines useful properties.At the most basic level you need just two properties controller and templateUrl.
app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "page1.html", controller: 'Controller1' }) .when("/page2", { templateUrl : "page2.html", controller: 'Controller2' }) .when("/page3", { templateUrl : "page3.html", controller: 'Controller3', }) .when("/page4", { templateUrl : "page4.html", controller: 'Controller4', }); });
To add multiple routes you can use chain of when() methods.
When method takes location or URL pattern as one of the parameters.If the requested URL matches this pattern then matching route is used to display the view.
For example in the above example when the application is requested then page1.html is loaded by default.When /page2 is requested then page2.html
is loaded.
4. Define ng-view in the main page.
To display the content of the matching file,add ng-view directive in the main html page.The ng-view directive renders the template of the selected route.Include it in main html page ,e.g index.html
<ng-view> </ng-view>
Leave a Reply