AngularJS : Routing Template files with sample code (routeProvider)

With help of angular-route we can able to route the template files in our AngularJS application based on user request. In routeprovider we will specify the template path and Controller for the each templates.

Syntax: 

$routeProvider
  .when('URL', {
    templateUrl: TEMPLATE_URL,
    controller: CONTROLLER
  });

Example:

File Structure:

 - index.html
 - js
    - angular-1.5.5.js
    - angular-route.min.js
    - app.js
 - template
    - welcome.html
    - base.html

app.js 

'use strict';
 
var serviceApp = angular.module('serviceApp', ['ngRoute']);
 
// Routers details.
serviceApp.config(['$routeProvider', function($routeProvider, $locationProvider) {
  $routeProvider
    .when('/welcome', {
      templateUrl: 'template/welcome.html',
      controller: 'welcomeController'
    })
    .when('/base', {
      templateUrl: 'template/base.html',
      controller: 'welcomeController'
    })
    .otherwise({
      redirectTo: '/welcome'
    });
}])

HTML

 

index.html:
----------
<html>
	<head>
		<title>Login</title>
    <script src = "js/angular-1.5.5.js"></script>
    <script src = "js/angular-route.min.js"></script>
    <script src = "js/app.js"></script>
  </head>
  <body>
    <div ng-app="serviceApp" class="content">
      <div ng-view></div>
    </div>
    <div class="footer">
    </div>
  </body>
</html>
 
 
welcome.html:
------------
<div ng-app="baseApp" ng-controller = "welcomeController">
	<h3>Welcome to CodeExpertz</h3>
</div>
 
 
base.html:
---------
<div ng-app="baseApp" ng-controller = "baseController">
	<h3>User List</h3>
	<form name = "userList" novalidate>
		<button ng-click="getUserList()">Get users</button>
	</form>
 
	<h3>Create User</h3>
	<form name = "createUser" novalidate>
		Username <input name = "userName" type="text" ng-model = "userName" required>
		Password <input name = "userPassword" type="password" ng-model = "userPassword" required>
		<button ng-click="createUser()">Create User</button>
	</form>
</div>
Category: