1.

How does routing work in AngularJS?

Answer»

Routing enables us to create different URLs according to different contents in our app which in turn enables the users of the application to bookmark the contents as per their requirements. The route is that URL that can be bookmarked. Routing also helps in developing SPA (Single Page Applications) i.e create a single HTML page and update that page dynamically as and when the user interacts.

AngularJS supports routing by making use of its routing module called “ngRoute”. This module acts according to the URL. Whenever a user requests for a specific route/URL, the routing engine of the module, also called $routeProvider, renders the view based on that URL and defines what controller acts on this view - all based on the routing rules defined.

Consider the below snippet:

var myApp = angular.module('routingExample', ['ngRoute']);myApp.config(function ($routeProvider) { $routeProvider.when('/', { templateUrl: '/login-page.html', controller: 'loginPageController' }).when('/employee/:empName', { templateUrl: '/employee-page.html', controller: 'employeeController' }).otherwise({ redirectTo: "/" });})

In the above example, we can see that to implement routing, we need to follow the below steps:

  • While creating the application module, pass ‘ngRoute’ as the dependency module like below:
var myApp = angular.module('routingExample', ['ngRoute']);
  • Next, configure the routing rules for the application module by making use of the config() method by taking the $routeProvider service as the dependency.
  • The $routeProvider.when(path, route) method is used for configuring the rules of routing where the first parameter defines what is the request URL and the second parameter defines the object CONTAINING the template, controller, and other PROPERTY details that need to function upon requesting the URL.
    • In the given example, if the user requests for “/login-page.html”, then INJECT login-page.html into the view and use the loginPageController.
    • For the URL “/employee/:empName” URL, the :empName refers to the URL parameter dynamically populated in the URL.
    • The otherwise() method is used for redirecting to the default or base URL for any other requests that are not part of the rules CONFIGURED.


Discussion

No Comment Found