Thursday, January 5, 2017

Simple Routing in AngularJS

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



Output:















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) {
    $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"
        })
        .otherwise({
            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">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></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>
</head>
<body>
    <center>
        <a href="#/home">Home</a> |
        <a href="#/books">Books</a> |
        <a href="#/customers">Customers</a>

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

    </center>
</body>
</html>


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

<h1>{{message}}</h1>


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