Fundamentals of Routing

Introduction

A single-page application, or SPA, is a website that uses a central webpage that includes a special section to display the contents of other webpages. With SPA, there is no reason for the user to leave one webpage to view the contents of another. The user requests something and the webserver sends the appropriate content to simply update the section that is made to display that particular content. We have already seen that both ASP.NET and AngularJS provide many features for SAPs.

Practical LearningPractical Learning: Introducing Routing

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New Project...
  3. In the New Project dialog box, make sure ASP.NET Web Application (.NET Framework) is selected in the middle list.
    Change the Name of the project to SunriseResidence1
  4. Click OK
  5. In the New ASP.NET Web Application, click the MVC icon and click OK
  6. In the So
  7. In the Solution Explorer, right-click Content -> Add -> Style Sheet
  8. Type SunriseResidence
  9. Click OK
  10. Create some styles as follows:
    body {
        background-color: #FFFFFF;
    }
    
    .bold               { font-weight:      600;               }
    .blue               { color:            #0d3bcf;           }
    .maroon             { color:            #800000;           }
    .top-border         { padding-top:      1.05em;
                          border-top:       1px solid #800000; }
    .topic-title        { color:            maroon;
                          padding-bottom:   0.25em;
                          border-bottom:    1px solid #800000; }
    .menu-holder        { margin:           auto;
                          width:            450px;             }
    .rm-contents        { margin:           auto;
                          width:            500px;
                          height:           2.80em;
                          background-color: #530505;
                          border:           1px solid black;   }
    .rm-list            { list-style:       none;              }
    .rm-list li         { float:            left;              }
    .rm-list li a       { padding:          8px;
                          display:          block;
                          text-align:       center;
                          color:            azure;
                          text-decoration:  none; 
                          border:           1px solid #530505; }
    .rm-list li a:hover { background-color: #740b0b;
                          border-left:      1px solid maroon;
                          border-right:     1px solid maroon;  }
    .navbar-inverse .navbar-nav > .active > a,
    .navbar-inverse .navbar-nav > .active > a:hover,
    .navbar-inverse .navbar-nav > .active > a:focus {
        color: lightyellow;
        background-color: #800000;
    }
    .navbar-fixed-top   { background-color: #530505;           }
    .common-font        { font-family:      Georgia, Garamond, 'Times New Roman' , serif; }
  11. In the Solution Explorer, expand Controllers and double-click HomeController.cs
  12. Create an action method named RentalManagement
    using System.Web.Mvc;
    
    namespace SunriseResidence1.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "We offer comfort. We advocate convenience. And we support our tenants.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Please contact us today for all your rental concerns.";
    
                return View();
            }
    
            public ActionResult RentManagement() => View();
        }
    }
  13. In the document, right-click RentManagement() and click Add View...
  14. In the Add View dialog box, make sure the View Name text box displays RentManagement. Click Add
  15. In the Solution Explorer, under Views, expand Shared and double-click _Layout.cshtml
  16. Type the following code:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - Sunrise Residence</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("Sunrise Residence", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Rent Management", "RentManagement", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
        </div>
    
        <footer class="top-border container common-font">
            <p class="text-center">&copy; @DateTime.Now.Year - Sunrise Residence</p>
        </footer>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>

Introduction to Routing in AngularJS

One way AngularJS implements SPAs is by using custom directives and components. One more feature available in AngularJS consists of indicating to the webserver what Web content to display in a reserved section of a central webpage. This is referred to as routing. As always, you have many options. To support routing, AngularJS provides a special module named ngRoute. Before using it, there are a few steps you must follow.

A Library for Routing

You must first have the right library. You can download and install it. To do this in Microsoft Visual Studio, after starting a project, in the Solution Explorer, right-click the name of the project and click Manage NuGet Packages... In the NuGet: tab, click Browse and type angularjs (you will need to be connected to the Internet because Microsoft Visual Studio will have to download the library). In the list of options that come up, click AngularJS.Route. Click Install. If a Preview message box comes up, read it and click OK. This will install both angular-route.js and angular-route.min.js files, among others. Alternatively, you can visit the AngularJS website, download, and install the route library.

In your project or the document where you are writing your code, in addition to the AngularJS file that we have used so far, you must add a reference to the angular-route.js (and/or the angular-route.min.js) file(s).

ApplicationPractical Learning: Introducing the Routing Library

  1. In the Solution Explorer, right-click SunriseResidence1 and click Manage NuGet Packages...
  2. In the NuGet tab, click Browser and, in the text box, type angular
  3. In the list, click AngularJS.Route

    AngularJS Route Installation

  4. Click Install.
    If a message box displays, click OK
  5. Click the RentManagement.cshtml tab to access it
  6. Change the document as follows:
    @{
        ViewBag.Title = "Rent Management";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <h2 class="text-center blue common-font bold">Apartments Rental Management</h2>
  7. In the Solution Explorer, right-click Scripts -> Add > JavaScript File
  8. Type RentManagement as the name of the file
  9. Click OK
  10. In the document, type the following code:
    var appSunrise = angular.module('SunriseResidence', []);

A Dependent Module

When creating an AngularJS module in your code, you must indicate that your module depends on the ngRoute module. As you may know already, to indicate that a module depends on another, add the depending module in the array that is the second argument to the module() function. It is passed as a string (in single or double-quotes). Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Country's Summary</title>
<script src="../Scripts/angular.js"></script>
<script src="angular-route.js"></script>
</head>
<body ng-app="webPageRouting">

<script type="text/javascript">
    angular.module('webPageRouting', ['ngRoute']);
</script>
</body>
</html>

Then you are ready to perform routing operations in AngularJS.

ApplicationPractical Learning: Introducing the AngularJS Router

A Route Provider

To support routing, AngularJS is equipped with a service named $routeProvider. To use this service, since it is a provider, we saw that you should (must) pass it as an argument to the function passed to config(). This can be done as follows:

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

app.config(function ($routeProvider) {

});

Of course if necessary, you can pass additional arguments, such as additional services, to the function.

ApplicationPractical Learning: Introducing a Route Provider

  1. Change the code as follows:
    var appSunrise = angular.module('SunriseResidence', ['ngRoute']);
    
    appSunrise.config(function ($routeProvider) {
    
    });
  2. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  3. Change the document as follows:
    using System.Web;
    using System.Web.Optimization;
    
    namespace SunriseResidence1
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js",
                            "~/Scripts/angular.js",
                            "~/Scripts/angular-route.js",
                            "~/Scripts/RentManagement.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js",
                          "~/Scripts/respond.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/SunriseResidence.css"));
            }
        }
    }

Primary Characteristics of AngularJS Routing

Introduction to the Links of a Routing System

To implement routing, you can first create the link(s) that will indicate the document(s) to be accessed. The primary formula to create a link is:

<a href="#!link-name">link-string</a>

Create the link using the same symbols and words as in HTML. Instead of an address, use #! followed by a name you will programmatically use to refer to the link (later). Here is an example:

<a href="#!Vehicles">. . .</a>

Between the start and end tags, provide the text that will display to the visitor. Here is an example:

<a href="#!Vehicles">Vehicles</a>

In the same way, you can create as many links as you want. You can create them in a list, a table, etc.

Practical LearningPractical Learning: Introducing Routing Links

  1. Click the RentManagement.cshtml tab and change the document as follows:
    @{
        ViewBag.Title = "Rent Management";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <div ng-app="SunriseResidence">
        <h2 class="text-center blue common-font bold">Apartments Rental Management</h2>
    
        <div class="rm-contents">
            <ul class="rm-list menu-holder">
                <li><a href="#!Apartments">Apartments</a></li>
                <li><a href="#!RentContracts">Rent Contracts</a></li>
                <li><a href="#!Payments">Payments</a></li>
                <li><a href="#!Employees">Employees</a></li>
            </ul>
        </div>
    </div>
  2. To execute the application, on the main menu, click Debug and click Start Without Debugging

    Primary Characteristics of AngularJS Routing

  3. Return to your programming environment

A Directive Section

As you may know already (from ASP.NET MVC), in AngularJS, you must specify the section where the contents of the other pages would display. This is done by adding a directive named ng-view from the ngView object. You can create it as an element. Here is an example:

. . .
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-route.js"></script>
</head>
<body ng-app="webPageRouting">
    . . .

    <ng-view></ng-view>

<script type="text/javascript">
    var app = angular.module('webPageRouting', ['ngRoute']);

    app.config(function ($routeProvider) {

    });
</script>
</body>
</html>

You can also create it an attribute to an HTML element. Here is an example:

<div ng-view></div>

Or you can specify it as a CSS class. Here is an example:

<div class="ng-view"></div>

Practical LearningPractical Learning: Introducing the Directive View

  1. Change document as follows:
    @{
        ViewBag.Title = "Rent Management";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <div ng-app="SunriseResidence">
        <h2 class="text-center blue common-font bold">Apartments Rental Management</h2>
    
        <div class="rm-contents">
            <ul class="rm-list menu-holder">
                <li><a href="#!Apartments">Apartments</a></li>
                <li><a href="#!RentContracts">Rent Contracts</a></li>
                <li><a href="#!Payments">Payments</a></li>
                <li><a href="#!Employees">Employees</a></li>
            </ul>
        </div>
    
        <div class="top-border">
            <ng-view></ng-view>
        </div>
    </div>
  2. To save the file, on the Standard toolbar, click the Save button Save All
  3. Return to the browser and refresh it

    Introducing the Directive Section View

  4. Return to your programming environment

When a Name is Accessed

To use the $routeProvider provider, you must create a navigation scheme as a list of options to control this service. As a result, the $routeProvider service works like a switch statement of most computer languages. When it comes to the $routeProvider service, each case is dealt with by a method named when. The syntax of this method is:

when(path, route);

You must attach each call of this function to a $routeProvider object. Therefore, the formula to use this service is:

$routeProvider.when(path1, route1).when(path2, route2)...when(path_n, route_n);

The $routeProvider.when() method takes two arguments. The first argument is the name you would have created for a link in the view. That name is passed as a string. It should be preceded by a a forward slash '/'. Here is an example:

. . .
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-route.js"></script>
</head>
<body ng-app="webPageRouting">
    <h1>:: Country's Review ::</h1>
    <p><a href="#!History">Historical Events</a></p>

    <ng-view></ng-view>

<script type="text/javascript">
    var app = angular.module('webPageRouting', ['ngRoute']);

    app.config(function ($routeProvider) {
        $routeProvider.when('/History', . . .)
    });
</script>
</body>
</html>

A Template for a Link

The second argument is an object that specifies what to display when a link is clicked:

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

app.config(function ($routeProvider) {
    $routeProvider.when('/History', {})
});

You have many options. As seen with custom directives and Components, to create the content to display, add a template property to the object and set its value as the desired text. The value can contain simple text, HTML code, and CSS format. Here are two examples:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Country's Review</title>
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-route.js"></script>
</head>
<body ng-app="webPageRouting">
    <h1>:: Country's Review ::</h1>
    <ul>
        <li><a href="#!History">Historical Events</a></li>
        <li><a href="#!Geography">Geographical Studies</a></li>
    </ul>
    
    <hr color="red" />
    
    <ng-view></ng-view>

<script type="text/javascript">
    var app = angular.module('webPageRouting', ['ngRoute']);

    app.config(function ($routeProvider) {
        $routeProvider
            .when('/History', {
                template: '<h1>History</h1><p>The first part of this document provides a short review of the history of this country.</p>'
            })
            .when('/Geography', {
                template: '<h1>Geography</h1><p>Here is a review of moutains, valleys, rivers, and national parks of the country.</p>'
            })
    });
</script>
</body>
</html>

Practical LearningPractical Learning: Introducing Link Templates

  1. Click the RentManagement.js tab and change the document as follows:
    var appSunrise = angular.module('SunriseResidence', ['ngRoute']);
    
    appSunrise.config(function ($routeProvider) {
        $routeProvider.
            when('/Apartments', {
                template: "<h3 class='text-center common-font blue bold'>Apartments</h2>" +
                    "<p class='common-font'>This is a list of the apartments on rent by this company.</p>"
            }).
            when('/RentContracts', {
                template: "<h3 class='text-center common-font blue bold'>Rent Contracts</h2>" +
                    "<p class='common-font'>Here are the details of the rent contracts of the current residents.</p>"
            }).
            when('/Payments', {
                template: "<h3 class='text-center common-font blue bold'>Payments</h2>" +
                    "<p class='common-font'>This section shows the rent payments made by the tenants.</p>"
            }).
            when('/Employees', {
                template: "<h3 class='text-center common-font blue bold'>Employees</h2>" +
                    "<p class='common-font'>Meet our staff members, including employees, contractors, technicians, associates, etc.</p>"
            });
    });
  2. To save the file, on the Standard toolbar, click the Save button Save
  3. Return to the browser and refresh it

    Introducing the Directive Section View

  4. Click each of the links:

    Introduction to Link Templates

    Introduction to Link Templates

    Introduction to Link Templates

    Introduction to Link Templates

  5. Close the browser and return to your programming environment

Options on Configuring Routing

The Route Home

To specify the default page, start its address as #/! followed by the string you want the user so see, such as Home or something like that. Pass the first argument of the when() argument as a forward slash. Set the value of the template property anyway you want.

Practical LearningPractical Learning: Adding the Ooute Home

  1. Access the RentManagement.cshtml file and change it as follows:
    @{
        ViewBag.Title = "Rent Management";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <div ng-app="SunriseResidence">
        <h2 class="text-center blue common-font bold">Apartments Rental Management</h2>
    
        <div class="rm-contents">
            <ul class="rm-list menu-holder">
                <li><a href="#/!Home">Home</a></li>
                <li><a href="#!Apartments">Apartments</a></li>
                <li><a href="#!RentContracts">Rent Contracts</a></li>
                <li><a href="#!Payments">Payments</a></li>
                <li><a href="#!Employees">Employees</a></li>
            </ul>
        </div>
    
        <div class="top-border">
            <ng-view></ng-view>
        </div>
    </div>
  2. Access the RentManagement.js file and change it as follows:
    var appSunrise = angular.module('SunriseResidence', ['ngRoute']);
    
    appSunrise.config(function ($routeProvider) {
        $routeProvider.
            when('/', {
                template: "<h3 class='text-center common-font maroon bold'>Welcome</h2>" +
                    "<p class='common-font'>Here is introductory information you should have about our residence.</p>"
            }).
            when('/Apartments', {
                template: "<h3 class='text-center common-font blue bold'>Apartments</h2>" +
                    "<p class='common-font'>This is a list of the apartments on rent by this company.</p>"
            }).
            when('/RentContracts', {
                template: "<h3 class='text-center common-font blue bold'>Rent Contracts</h2>" +
                    "<p class='common-font'>Here are the details of the rent contracts of the current residents.</p>"
            }).
            when('/Payments', {
                template: "<h3 class='text-center common-font blue bold'>Payments</h2>" +
                    "<p class='common-font'>This section shows the rent payments made by the tenants.</p>"
            }).
            when('/Employees', {
                template: "<h3 class='text-center common-font blue bold'>Employees</h2>" +
                    "<p class='common-font'>Meet our staff members, including employees, contractors, technicians, associates, etc.</p>"
            });
    });
  3. Click the SunriseResidence.css tab to access it
  4. In the document, locate the menu-holder style and change its width value to 500
    . . . No Change
    .menu-holder        { margin:           auto;
                          width:            500px;             }
    . . . No Change
  5. To execute the application, on the main menu, click Debug - Start Without Debugging
  6. Return to the browser and refresh it
  7. Click Rent Management and click the Home link:

    Introduction to Link Templates

  8. Close the browser and return to your programming environment

If a Route Definition is Not Found

After specifying the target links of a $routeProvider service, when the user clicks a link, if there is no corresponding document, nothing will happen. This may create confusion to the visitor. To let you provide a default content, the $routeProvider object is equipped with a method named otherwise. If the $routeProvider service and its when() method is equivalent to the switch statement of the computer languages, its otherwise() method corresponds to the default clause.

The $routeProvider.otherwise() method takes one argument that can be a string or an object. If you pass it as an object, you can add a template property to it and set its value as the default text to display. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Country's Review</title>
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-route.js"></script>
</head>
<body ng-app="webPageRouting">
    <h1>:: Country's Review ::</h1>
    <ul>
        <li><a href="#!History">Historical Events</a></li>
        <li><a href="#!Geography">Geographical Studies</a></li>
        <li><a href="#!Website">Web Site</a></li>
    </ul>
    
    <hr color="red" />
    
    <ng-view></ng-view>

<script type="text/javascript">
    var app = angular.module('webPageRouting', ['ngRoute']);

    app.config(function ($routeProvider) {
        $routeProvider.
            when('/History', {
                template: '<h1>History</h1><p>The first part of this document provides a short review of the history of this country.</p>'
            }).
            when('/Geography', {
                template: '<h1>Geography</h1><p>Here is a review of moutains, valleys, rivers, and national parks of the country.</p>'
            }).
            otherwise({
                template: '<p>Sorry for the inconvenience, the content is under development...</p>'
            })
    });
</script>
</body>
</html>

Practical LearningPractical Learning: Providing an All Alternate Route

  1. Click the RentManagement.js tab and change the document as follows:
    var appSunrise = angular.module('SunriseResidence', ['ngRoute']);
    
    appSunrise.config(function ($routeProvider) {
        $routeProvider.
            when('/', {
                template: "<h2 class='text-center common-font maroon bold'>Welcome</h2>" +
                    "<p class='common-font'>Here is introductory information you should have about our residence.</p>"
            }).
            when('/Apartments', {
                template: "<h3 class='text-center common-font blue bold'>Apartments</h2>" +
                    "<p class='common-font'>This is a list of the apartments on rent by this company.</p>"
            }).
            when('/RentContracts', {
                template: "<h3 class='text-center common-font blue bold'>Rent Contracts</h2>" +
                    "<p class='common-font'>Here are the details of the rent contracts of the current residents.</p>"
            }).
            when('/Payments', {
                template: "<h3 class='text-center common-font blue bold'>Payments</h2>" +
                    "<p class='common-font'>This section shows the rent payments made by the tenants.</p>"
            }).
            when('/Employees', {
                template: "<h3 class='text-center common-font blue bold'>Employees</h2>" +
                    "<p class='common-font'>Meet our staff members, including employees, contractors, technicians, associates, etc.</p>"
            }).
            otherwise({
                template: "<p>This section is under construction...</p>"
            });
    });
  2. Click the RentManagement.cshtml tab and change the document as follows:
    @{
        ViewBag.Title = "Rent Management";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <div ng-app="SunriseResidence">
        <h2 class="text-center blue common-font bold">Apartments Rental Management</h2>
    
        <div class="rm-contents">
            <ul class="rm-list menu-holder">
                <li><a href="#/!Home">Home</a></li>
                <li><a href="#!Apartments">Apartments</a></li>
                <li><a href="#!RentContracts">Rent Contracts</a></li>
                <li><a href="#!Payments">Payments</a></li>
                <li><a href="#!Employees">Employees</a></li>
                <li><a href="#!Security">Security/Maintenance</a></li>
            </ul>
        </div>
    
        <div class="top-border">
            <ng-view></ng-view>
        </div>
    </div>
  3. Click the SunriseResidence.css tab to access it
  4. In the document, change the width value of the menu-holder style and to 650
  5. Change the width value of the tm-contents style and to 650
    . . . No Change
    
    .menu-holder        { margin:           auto;
                          width:            650px;             }
    .rm-contents        { margin:           auto;
                          width:            600px;
                          height:           2.80em;
                          background-color: #530505;
                          border:           1px solid black;   }
    
    . . . No Change
  6. To execute, on the main menu, click Debug - Start Without Debugging
  7. Click the Rent Management link:

    Label

  8. Click the Police Precinct link:

    If a Route Definition is Not Found

  9. Close the browser and return to your programming environment
  10. Click the RentManagement.cshtml tab and remove the last link that was created:
    @{
        ViewBag.Title = "Rent Management";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <div ng-app="SunriseResidence">
        <h2 class="text-center blue common-font bold">Apartments Rental Management</h2>
    
        <div class="rm-contents">
            <ul class="rm-list menu-holder">
                <li><a href="#/!Home">Home</a></li>
                <li><a href="#!Apartments">Apartments</a></li>
                <li><a href="#!RentContracts">Rent Contracts</a></li>
                <li><a href="#!Payments">Payments</a></li>
                <li><a href="#!Employees">Employees</a></li>
            </ul>
        </div>
    
        <div class="top-border">
            <ng-view></ng-view>
        </div>
    </div>
  11. Click the SunriseResidence.css tab to access it
  12. Change the width value of the menu-holder style to 500 and the width value of the tm-contents style to 550
    . . . No Change
    
    .menu-holder        { margin:           auto;
                          width:            500px;             }
    .rm-contents        { margin:           auto;
                          width:            550px;
                          height:           2.80em;
                          background-color: #530505;
                          border:           1px solid black;   }
    
    . . . No Change

Controlling the Contents of a Route

As seen with directives, you can use a controller to create the content that will display when a routing link is clicked. In the body of the function of the controller, create one or more properties attached to a this object or to a $scope service. In the object of the when() method, add a controller property and set its value as the name of the controller you had created. If you had attached the properties of the controller using the this object, create an instance of the controller. Still in the when() object, add a template property. In its value, create the necessary {{}} placeholders and fill each with the desired properties from the controller. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Country's Review</title>
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-route.js"></script>
</head>
<body ng-app="webPageRouting">
    <h1>:: Country's Review ::</h1>
    <ul>
        <li><a href="#!History">Historical Events</a></li>
        <li><a href="#!Geography">Geographical Studies</a></li>
    </ul>

    <hr color="red" />

    <ng-view></ng-view>

<script type="text/javascript">
    var app = angular.module('webPageRouting', ['ngRoute']);

    app.controller('HistoryController', [function () {
        this.title = 'Historical Events';
        this.content = 'The first part of this document provides a short review of the history of this country.'
    }]);
    app.config(function ($routeProvider) {
        $routeProvider.
            when('/History', {
                controller: 'HistoryController as hc',
                template: '<h1>{{hc.title}}</h1><p>{{hc.content}}</p> '
            }).
            when('/Geography', {
                template: '<h1>Geography</h1><p>Here is a review of moutains, valleys, rivers, and national parks of the country.</p>'
            })
    });
    </script>
</body>
</html>

Practical LearningPractical Learning: Controlling the Contents of a Route

  1. To create a common controller for all routes, change the RentManagement.js document as follows:
    var appSunrise = angular.module('SunriseResidence', ['ngRoute']);
    
    appSunrise.controller('RentManagementController', ['$scope', function ($scope) {
        $scope.apartmentsTitle = "Apartments";
        $scope.apartmentsDescriptions = "This is the general apartments listing of our community.";
        $scope.contractsTitle = "Rent Contracts";
        $scope.contractsDetails = "This is an overview of the various contracts of our multiple tenants.";
        $scope.paymentsTitle = "Rent Payments";
        $scope.paymentsDetails = "We use this section to track the rent payments of the residents.";
        $scope.employeesTitle = "Employees";
        $scope.employeesInformation = "This section contains a list of our staff members: employees, technicians/contractors, interns, etc.";
    }]);
    
    appSunrise.config(function ($routeProvider) {
        $routeProvider.
            when('/', {
                template: "<h2 class='text-center common-font maroon bold'>Welcome</h2>" +
                    "<p class='common-font'>Here is introductory information you should have about our residence.</p>"
            }).
            when('/Apartments', {
                controller: "RentManagementController",
                template: "<h3 class='text-center common-font blue bold'>{{apartmentsTitle}}</h2>" +
                    "<p class='common-font'>{{apartmentsDescriptions}}</p>"
            }).
            when('/RentContracts', {
                controller: "RentManagementController",
                template: "<h3 class='text-center common-font blue bold'>{{contractsTitle}}</h2>" +
                    "<p class='common-font'>{{contractsDetails}}</p>"
            }).
            when('/Payments', {
                controller: "RentManagementController",
                template: "<h3 class='text-center common-font blue bold'>{{paymentsTitle}}</h2>" +
                    "<p class='common-font'>{{paymentsDetails}}</p>"
            }).
            when('/Employees', {
                controller: "RentManagementController",
                template: "<h3 class='text-center common-font blue bold'>{{employeesTitle}}</h2>" +
                    "<p class='common-font'>{{employeesInformation}}</p>"
            }).
            otherwise({
                template: "<p>This section is under construction...</p>"
            });
    });
  2. To execute, on the main menu, click Debug - Start Without Debugging
  3. Click the Rent Management link:

    Label

  4. Click each of the links:

    Controlling the Contents of a Route

    Controlling the Contents of a Route

    Controlling the Contents of a Route

    Controlling the Contents of a Route

    Controlling the Contents of a Route

  5. Return to your programming environment
  6. To create a different controller for each route, change the RentManagement.js document as follows:
    var appSunrise = angular.module('SunriseResidence', ['ngRoute']);
    
    appSunrise.controller('ApartmentsController', ['$scope', function ($scope) {
        $scope.apartmentsTitle = "Apartments";
        $scope.apartmentsDescriptions = "This is the general apartments listing of our community.";
    }]).controller('RentContractsController', ['$scope', function ($scope) {
        $scope.contractsTitle = "Rent Contracts";
        $scope.contractsDetails = "This is an overview of the various contracts of our multiple tenants.";
    }]).controller('PaymentsController', ['$scope', function ($scope) {
        $scope.paymentsTitle = "Rent Payments";
        $scope.paymentsDetails = "We use this section to track the rent payments of the residents.";
    }]).controller('EmployeesController', ['$scope', function ($scope) {
        $scope.employeesTitle = "Employees";
        $scope.employeesInformation = "This section contains a list of our staff members: employees, technicians/contractors, interns, etc.";
    }]);
    
    appSunrise.config(function ($routeProvider) {
        $routeProvider.
            when('/', {
                template: "<h2 class='text-center common-font maroon bold'>Welcome</h2>" +
                    "<p class='common-font'>Here is introductory information you should have about our residence.</p>"
            }).
            when('/Apartments', {
                controller: "ApartmentsController",
                template: "<h3 class='text-center common-font blue bold'>{{apartmentsTitle}}</h2>" +
                    "<p class='common-font'>{{apartmentsDescriptions}}</p>"
            }).
            when('/RentContracts', {
                controller: "RentContractsController",
                template: "<h3 class='text-center common-font blue bold'>{{contractsTitle}}</h2>" +
                    "<p class='common-font'>{{contractsDetails}}</p>"
            }).
            when('/Payments', {
                controller: "PaymentsController",
                template: "<h3 class='text-center common-font blue bold'>{{paymentsTitle}}</h2>" +
                    "<p class='common-font'>{{paymentsDetails}}</p>"
            }).
            when('/Employees', {
                controller: "EmployeesController",
                template: "<h3 class='text-center common-font blue bold'>{{employeesTitle}}</h2>" +
                    "<p class='common-font'>{{employeesInformation}}</p>"
            }).
            otherwise({
                template: "<p>This section is under construction...</p>"
            });
    });
  7. To save the file, on the Standard toolbar, click the Save button Save
  8. Return to the browser and refresh it
  9. Click each of the links
  10. Close the browser and return to your programming environment
  11. To create each controller in its own file, in the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  12. Type ApartmentsController as the name of the file
  13. Click OK
  14. In the empty document, type the following code:
    appSunrise.controller('ApartmentsController', ['$scope', function ($scope) {
        $scope.apartmentsTitle = "Apartments";
        $scope.apartmentsDescriptions = "This is the general apartments listing of our community.";
    }]);
  15. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  16. Type RentContractsController
  17. Click OK
  18. Type the following code:
    appSunrise.controller('RentContractsController', ['$scope', function ($scope) {
        $scope.contractsTitle = "Rent Contracts";
        $scope.contractsDetails = "This is an overview of the various contracts of our multiple tenants.";
    }]);
  19. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  20. Type PaymentsController
  21. Click OK
  22. Type some code as follows:
    appSunrise.controller('PaymentsController', ['$scope', function ($scope) {
        $scope.paymentsTitle = "Rent Payments";
        $scope.paymentsDetails = "We use this section to track the rent payments of the residents.";
    }]);
  23. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  24. Type EmployeesController
  25. Click OK
  26. Type some code as follows:
    appSunrise.controller('EmployeesController', ['$scope', function ($scope) {
        $scope.employeesTitle = "Employees";
        $scope.employeesInformation = "This section contains a list of our staff members: employees, technicians/contractors, interns, etc.";
    }]);
  27. Access the RentManagement.js file and delete the whole code section that has the controllers:
    var appSunrise = angular.module('SunriseResidence', ['ngRoute']);
    
    appSunrise.config(function ($routeProvider) {
        $routeProvider.
            when('/', {
                template: "<h2 class='text-center common-font maroon bold'>Welcome</h2>" +
                    "<p class='common-font'>Here is introductory information you should have about our residence.</p>"
            }).
            when('/Apartments', {
                controller: "ApartmentsController",
                template: "<h3 class='text-center common-font blue bold'>{{apartmentsTitle}}</h2>" +
                    "<p class='common-font'>{{apartmentsDescriptions}}</p>"
            }).
            when('/RentContracts', {
                controller: "RentContractsController",
                template: "<h3 class='text-center common-font blue bold'>{{contractsTitle}}</h2>" +
                    "<p class='common-font'>{{contractsDetails}}</p>"
            }).
            when('/Payments', {
                controller: "PaymentsController",
                template: "<h3 class='text-center common-font blue bold'>{{paymentsTitle}}</h2>" +
                    "<p class='common-font'>{{paymentsDetails}}</p>"
            }).
            when('/Employees', {
                controller: "EmployeesController",
                template: "<h3 class='text-center common-font blue bold'>{{employeesTitle}}</h2>" +
                    "<p class='common-font'>{{employeesInformation}}</p>"
            }).
            otherwise({
                template: "<p>This section is under construction...</p>"
            });
    });
  28. Access the BundleConfig.cs file and change it as follows:
    using System.Web.Optimization;
    
    namespace ApartmentsRentalCompany1
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js",
                            "~/Scripts/angular.js",
                            "~/Scripts/angular-route.js",
                            "~/Scripts/RentManagement.js",
                            "~/Scripts/PaymentsController.js",
                            "~/Scripts/EmployeesController.js",
                            "~/Scripts/ApartmentsController.js",
                            "~/Scripts/RentContractsController.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js",
                          "~/Scripts/respond.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/SunriseResidence.css"));
            }
        }
    }
  29. To execute the application, on the main menu, click Debug -> Start Without Debugging:
  30. Click the Rent Management link
  31. Click each of the link to make sure they work and to see the results
  32. Close the browser and return to your programming environment
  33. Close your programming environment

Previous Copyright © 2018-2022, FunctionX Next