Thursday, January 5, 2017

Simple Routing in AngularJS

Here I will show how to create a Simple Routing Application in AngularJS.


Create an empty application in VS and add the following Controllers and Html pages accordingly as shown in the image below.

Ones they are created Open MainApp.js File and ADD the following script in it.

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

app.config(function ($routeProvider) {
        .when("/home", {
            templateUrl: "/templates/Home.html",
            controller: "homeController"
        .when("/books", {
            templateUrl: "/templates/Books.html",
            controller: "booksController"
        .when("/customers", {
            templateUrl: "/templates/Customers.html",
            controller: "customersController"
            redirectTo: "/home"

In the above script we had created a Module with the Name AngularDemo, this AngularDemo is used in the Index.html page in the html tag, to do so Open Index.html page and ADD the script as shown

<!DOCTYPE html>
<html ng-app="AngularDemo">
    <script src=""></script>
    <script src="//"></script>
    <script src="Scripts/MainApp.js"></script>
    <script src="Scripts/HomeController.js"></script>
    <script src="Scripts/CustomersController.js"></script>
    <script src="Scripts/BooksController.js"></script>
        <a href="#/home">Home</a> |
        <a href="#/books">Books</a> |
        <a href="#/customers">Customers</a>

        <br />
        <div ng-view></div>


After that open Home.html page and ADD/replace with the below script


Open the remaining Html pages(Books.html and Customers.html) and ADD/replace with the above script.
Ones they are completed, Open HomeController.js file and Add below script

app.controller("homeController", ["$scope", function ($scope) {
    $scope.message = "This is Home Page";

Add the same code in the remaining controllers accordingly.

Download the Entire Code from Here

No comments:

Post a Comment