AngularJS Routing Application
angular.module('routingDemoApp',['ngRoute']) .config(['$routeProvider', function($routeProvider){ $routeProvider .when('/',{template:'This is the homepage'}) .when('/computers',{template:'This is the computers category page'}) .when('/printers',{template:'This is the printers page'}) .otherwise({redirectTo:'/'}); }]); [Try it Β»](#) Example Analysis: * 1. Loaded the JavaScript file for implementing routing: angular-route.js. * 2. Included the ngRoute module as a dependency module for the main application module. angular.module('routingDemoApp',['ngRoute']) * 3. Used the ngView directive. The HTML content inside this div will change based on the route. * 4. Configured $routeProvider. The AngularJS $routeProvider is used to define routing rules. module.config(['$routeProvider', function($routeProvider){ $routeProvider .when('/',{template:'This is the homepage'}) .when('/computers',{template:'This is the computers category page'}) .when('/printers',{template:'This is the printers page'}) .otherwise({redirectTo:'/'});}]); The config function of an AngularJS module is used to configure routing rules. By using the config API, we request to inject $routeProvider into our configuration function and use the $routeProvider.when API to define our routing rules. $routeProvider provides us with the when(path, object) & otherwise(object) functions to define all routes sequentially. The functions contain two parameters: * The first parameter is a URL or a URL regular expression rule. * The second parameter is the route configuration object. * * * ## Route Configuration Object AngularJS routing can also be implemented using different templates. The first parameter of the $routeProvider.when function is a URL or a URL regular expression rule, and the second parameter is the route configuration object. The syntax for the route configuration object is as follows: $routeProvider.when(url, { template: string, templateUrl: string, controller: string, function or array, controllerAs: string, redirectTo: string, function, resolve: object}); Parameter Description: * **template:** Use this parameter if we only need to insert simple HTML content into ng-view: .when('/computers',{template:'This is the computers category page'}) * **templateUrl:** Use this parameter if we only need to insert an HTML template file into ng-view: $routeProvider.when('/computers', { templateUrl: 'views/computers.html',}); The above code will fetch the content of the views/computers.html file from the server and insert it into the ng-view. * **controller:** A function, string, or array type. The controller function executed on the current template, generating a new scope. * **controllerAs:** A string type, specifying an alias for the controller. * **redirectTo:** The address to redirect to. * **resolve:** Specifies other modules that the current controller depends on. ### Example ## AngularJS ExampleHome
About
[Try it Β»](#)
YouTip