AngularJS tutorial || routing in angularJS

AngularJS tutorial, routing in angularJS, what is the ngRoute module in angularJS and what is $routeProvider in angularJS. let’s see angularJS routing with the example of a single page application in angularJS.

AngularJS routing

AngularJs is used to create a single-page application. AngularJS routing is very easy to make single-page applications. In this angularJS tutorial,

  1. How to use the ngRoute module.
  2. How to make a single page application in angularJS.

ngRoute module in angularJS.

ngRout is used to redirect other pages to your single-page application for more clarity let’s see an example or watch the video tutorial on the angular router.

Create a module and add the “ngRoute” as a dependency in the module.

var app =angular.module('myApp', ["ngRoute"]);

 $routeProvider in angularJS.

$routeProvider is used to configure a different route for a single page.

app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "index.html"
})
.when("/first", {
templateUrl : "first.html",
controller: "myCtrl2"
})
.when("/second", {
templateUrl : "second.html"
});
});

Create a single-page application in angularJS.

first.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>I am from first</h1>
{{msg}}
</body>
</html>

second.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>I am from second</h1>
{{msg}}
</body>
</html>

index.js

var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
  
    .when("/first", {
        templateUrl : "first.html",
        controller: "myCtrl"
    })
    .when("/second", {
        templateUrl : "second.html",
        	controller: "myCtrl2"
    });
    
});

app.controller('myCtrl',function($scope){
  $scope.msg = "I am From First"
});

app.controller('myCtrl2',function($scope){
  $scope.msg = "I am From Second"
});

 module and controller in angularJS