Fundamentals of AngularJS and Arrays

Introduction to this Array

AngularJS gets its fundamental concepts of arrays from JavaScript, and then adds some. To start, you can create an array in the constructor of a controller, as done in JavaScript. In AngularJS, you can attach the array to the this object. If you don't (yet) have the desired elements of the array, you can create it empty and assign it to a variable. Here is an example:

var app = angular.module("heroApp", []);
app.controller("HeroController", describe);

function describe() {
    this.characteristics = [];
}

Otherwise, if you have elements for the array, define it and assign it to a variable attached to the this object. Here is an example:

var appModule = angular.module("billsModule", []);
    appModule.controller("BillsController", present);

    function present() {
        this.customers = ["Joseph", "Patricia", "Anthony", "Valerie", "Cynthia"];
}

Practical LearningPractical Learning: Introducing Arrays

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the New Project dialog box, click ASP.NET Web Application (.NET Framework). Change project Name to CableCompany3
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, click the MVC icon and click OK
  6. In the Solution Explorer, right-click CableCompany3 and click Manage NuGet Packages...
  7. Click the Browser button.
    Do a search on AngularJS (you must be connected to the Internet)
  8. In the list, click angularjs:

    Microsoft Visual Studio - AngularJS Installation

  9. In the middle-right frame, click Install. If a dialog box comes up, read it and click OK
  10. To create a new CSS file, in the Solution Explorer, right-click Content -> Add -> New Item...
  11. In the left frame of the Add New Item dialog box, click Web and click Markup under it. In the middle frame, click Style Sheet
  12. Change the file Name to CableCompany
  13. Click Add
  14. Change the document as follows:
    body {
        background-color: white;
    }
    
    form                        { padding:          1em;
                                  margin:           auto;
                                  width:            550px;
                                  background-color: #e0d4c0;
                                  border:           1px solid maroon; }
    form div                    { padding:          4px;
                                  margin:           0 0 1px 0; }
    input[type=number]          { width:            80px;
                                  float:            right;
                                  border:           1px solid maroon; }
    input[type=number]:focus    { outline:          1px solid #ff6a00; }
    input[type=button]          { border:           0;
                                  border-radius:    10px;
                                  font-size:        14px;
                                  width:            130px;
                                  margin-left:      100px;
                                  background-color: brown;
                                  padding:          0.75em;
                                  color:            yellow; }
    input[type=button]:hover    { color:            white;
                                  cursor:           pointer;
                                  background-color: chocolate; }
    form > fieldset > div > div { margin:           0 0 5px 0; }
    .bold                       { font-weight:      600;       }
    .main-title                 { font-family:      'Times New Roman', Garamond, Georgia, serif;
                                  color:            maroon; }
    .caption                    { width:            11.45em;
                                  display:          table-cell; }
    .resulting-value            { width:            6em;
                                  background-color: white;
                                  display:          table-cell;
                                  border:           1px solid maroon; }
  15. In the Solution Explorer, right-click Scripts -> Add -> New Item...
  16. In the left frame of the Add New Item dialog box, click Web and, in the middle frame, click JavaScript File
  17. Change the Name of the file to BillPreparation
  18. Click Add
  19. In the empty document, type the following:
    var billModule = angular.module('appCableCompany', []);
    billModule.controller("BillsController", function () {
        this.estimate = function () {
            var packageType = this.PackageType; // 10 Channels, Standard (140 Channels), Performance (220)
            var packageFee = 0.00;
            var dvr =  Number(this.DVRService || 0);
            var sport =  Number(this.SportsPackage || 0);
    
            if (packageType == 'Standard') {
                packageFee = 34.50;
            }
            else if (packageType == 'Performance') {
                packageFee = 51.85;
            }
            else { // Basic
                packageFee = 29.25;
            }
    
            var subTotal = packageFee + dvr + sport;
            var fcc = subTotal * 0.00250881;
            var local = (subTotal + fcc) * 0.0372668;
            var state = (subTotal + fcc) * 0.0082493;
    
            this.fccFee = fcc;
            this.DVRService = dvr;
            this.countyTaxes = local;
            this.stateTaxes = state;
            this.subTotal = subTotal;
            this.SportsPackage = sport;
            this.CableTVPackageFee = packageFee;
            this.paymentAmount = subTotal + fcc + local + state;
        }
    });
  20. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  21. Change the document as follows:
    using System.Web.Optimization;
    
    namespace CableCompany3
    {
        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/BillPreparation.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"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/CableCompany.css"));
            }
        }
    }
  22. In the Solution Explorer, expand the Controllers folder and under it, double-click HomeController.cs to open it
  23. Add a method named BillEvaluation as follows:
    using System.Web.Mvc;
    
    namespace CableCompany3.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult BillEvaluation()
            {
                return View();
            }
        }
    }
  24. In the document, right-click inside the BillEvaluation() method and click Add View...
  25. In the dialog box, make sure the text box displays BillEvaluation and click Add
  26. Change the document as follows:
    @{
        ViewBag.Title = "Bill Evaluation";
    }
    
    <h1 class="text-center main-title bold">Eastern Shore Company and Production Entertainment</h1>
    <h2 class="text-center main-title bold">Bill Evaluation</h2>
    
    @Scripts.Render("~/bundles/jquery")
    
    <form name="BillEvaluation" method="post" ng-app="appCableCompany">
        <fieldset ng-controller="BillsController as pay">
            <legend>Cable TV Services</legend>
    
            <div class="row">
                <div class="col-md-6">
                    <div class="bold">Cable TV Package Type</div>
                    <table class="tbl-package">
                        <tr>
                            <td><label for="Basic">Basic</label></td>
                            <td class="text-left"><input type="radio" ng-model="pay.PackageType" id="Basic" value="Basic" ng-click="pay.estimate()" /></td>
                        </tr>
                        <tr>
                            <td><label for="Standard">Standard</label></td>
                            <td class="text-left"><input type="radio" ng-model="pay.PackageType" id="Standard" value="Standard" ng-click="pay.estimate()" /></td>
                        </tr>
                        <tr>
                            <td><label for="Performance">Performance</label></td>
                            <td class="text-left"><input type="radio" ng-model="pay.PackageType" id="Performance" value="Performance" ng-click="pay.estimate()" /></td>
                        </tr>
                    </table>
                    <div>
                        <label for="DVRService">DVR Service:</label>
                        <input type="number" id="DVRService" ng-model="pay.DVRService" ng-change="pay.estimate()" />
                    </div>
                    <div>
                        <label for="SportsPackage">Sports Package:</label>
                        <input type="number" id="SportsPackage" ng-model="pay.SportsPackage" ng-change="pay.estimate()" />
                    </div>
                </div>
                <div class="col-md-6">
                    <div>
                        <span class="caption bold">Package Fee:</span>
                        <span class="resulting-value">{{pay.CableTVPackageFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Sub-Total:</span>
                        <span class="resulting-value">{{pay.subTotal.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">FCC Fee:</span>
                        <span class="resulting-value">{{pay.fccFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">County Taxes:</span>
                        <span class="resulting-value">{{pay.countyTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">State Taxes:</span>
                        <span class="resulting-value">{{pay.stateTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Payment Amount:</span>
                        <span class="resulting-value">{{pay.paymentAmount | number:2}}</span>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
  27. In the Solution Explorer, click the button on the left of Views to expand it. In the same way, expand the Shared folder
  28. Under Shared, double-click _Layout.cshtml to open it
  29. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>ESCAPE - Bill Evaluation :: @ViewBag.Title</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("ESCAPE", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Bill Evaluation", "BillEvaluation", "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()
            <hr />
            <footer>
                <p class="text-center">&copy; @DateTime.Now.Year - ESCAPE (Eastern Shore Company and Production Entertainment)</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  30. To execute, on the main menu, click Debug -> Start Without Debugging
  31. Click the Bill Evaluation link

    Video Collection

  32. In the DVR Service text box, type 3.93
  33. In the Sports Package, type 9.28
  34. Click the Standard radio button:

    Video Collection

  35. Close the broser and return to your programming environment

JavaScript Loops in AngularJS

As mentioned already, AngularJS supports conditional statements in the constructor of a controller. Here is an example:

angular
    .module('tzonesModule', [])
    .controller('TZonesController', function () {
        var j = 0;
        this.continental = [];
        this.timeZones = [ 'Eastern', "Central", 'Mountain', "Pacific", 
                           "Atlantic", "Alaska", "Hawaii", 'Samoa', "Chamorro" ];

        for (var i = 0; i < 9; i++) {
            if (i < 4) {
                $scope.continental[j] = $scope.timeZones[i];
                j++;
            }
        }
    });

The {{}} placeholders of AngularJS don't allow the loop routines of JavaScript. This means that you cannot use the while, do...while, or for loops in a {{}} placeholder.

Routine Operations on Arrays

AngularJS gets its routine array operations from JavaScript. This means that, when you have created an array, it is automatically an object of type Array.

The number of elements in an array is represented by the length property of the Array class.

To add one or more new elements to an array, call the push() method that the array inherits from the Array class. Here are two examples of calling it:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="appToys">
    <div ng-controller="ToysController as play">
        <h1>Children Toys Store</h1>
        <p style="font-weight: 600">New Toy: <input type="text" ng-model="play.toyName" />
           <input type="button" value="Add" ng-click="play.add()" /></p>
    </div>

<script>
    var app = angular.module('appToys', []);
    app.controller('ToysController', inventorize);

    function inventorize() {
        this.toys = [ "Mini Point of Sale Station", "Drawing Black Board" ];

        this.toys.push("Kid Ferry Boat");

        this.add = function () {
            this.toys.push($scope.toyName);
            this.toyName = '';
        }   
    }
</script>
</body>
</html>

To remove an element from an array, you can call the pop() method that the array gets from the Array class.

Accessing the Elements of an Array

Introduction

As seen in JavaScript, to access an array as an object, simply use its name in a {{}} placeholder. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ESCAPE - Bill Evaluation</title>
<script src="angular.min.js"></script>
</head>
<body>
<h1>ESCAPE - Bill Evaluation</h1>

<form name="BillEvaluation" method="get" ng-app="billsModule">
    <table ng-controller="BillsController as pay">
        <tr>
            <td style="font-weight: 600; width: 100px">Customers:</td>
            <td><span class="itemNumber">{{pay.customers}}</span></td>
        </tr>
    </table>
</form>

<script>
    var appModule = angular.module("billsModule", []);
    appModule.controller("BillsController", present);

    function present() {
        this.customers = ["Joseph", "Patricia", "Anthony", "Valerie", "Cynthia"];
    }
</script>
</body>
</html>

This would produce:

Accessing the Members of an Array

You can use JavaScript conditional statements to perform regular operations in a controller. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Time Zones</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="tzonesModule" ng-controller="TZonesController as tzc">
<h1>Time Zones</h1>
<h2>US Time Zones</h2>
<ul>
    <li>{{tzc.timeZones[0]}}</li>
    <li>{{tzc.timeZones[1]}}</li>
    <li>{{tzc.timeZones[2]}}</li>
    <li>{{tzc.timeZones[3]}}</li>
    <li>{{tzc.timeZones[4]}}</li>
    <li>{{tzc.timeZones[5]}}</li>
    <li>{{tzc.timeZones[6]}}</li>
    <li>{{tzc.timeZones[7]}}</li>
    <li>{{tzc.timeZones[8]}}</li>
</ul>

<h2>Continental Time Zones</h2>
<ul>
    <li>{{tzc.continental[0]}}</li>
    <li>{{tzc.continental[1]}}</li>
    <li>{{tzc.continental[2]}}</li>
    <li>{{tzc.continental[3]}}</li>
</ul>

<script type="text/javascript">
    angular
        .module('tzonesModule', [])
        .controller('TZonesController', function () {
            var j = 0;
            this.continental = [];
            this.timeZones = ['Eastern', "Central", 'Mountain', "Pacific",
                "Atlantic", "Alaska", "Hawaii", 'Samoa', "Chamorro"];

            for (var i = 0; i < 9; i++) {
                if (i < 4) {
                    this.continental[j] = this.timeZones[i];
                    j++;
                }
            }
        });
</script>
</body>
</html>

This would produce:

JavaScript Loops in AngularJS

A Directive to Repeat a Routine

To support loops in a {{}} placeholder, AngularJS provides a directive named ng-repeat. You can apply it to any HTML tag that can repeat its display. The ng-repeat directive uses a value whose formula is:

variable-name in array-name

Start with a name that follows the rules of names of variables. This is followed by the in keyword and the name of the list or array whose elements you want to get. Outside the HTML tag, create a {{}} placeholder and include the variable-name of the value of the ng-repeat in them. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ESCAPE - Bill Evaluation</title>
<script src="angular.min.js"></script>
</head>
<body>
<h1>ESCAPE - Bill Evaluation</h1>
<h2>Customers</h2>

<form name="BillEvaluation" method="get" ng-app="billsModule">
    <div ng-controller="BillsController as pay">
        <p ng-repeat="client in pay.customers">{{client}}</p>
    </div>
</form>

<script>
    var appModule = angular.module("billsModule", []);
    appModule.controller("BillsController", present);

    function present() {
        this.customers = ["Joseph", "Patricia", "Anthony", "Valerie", "Cynthia"];
    }
</script>
</body>
</html>

This would produce:

Accessing the Members of an Array

The ng-repeat directive is usually used to create a list of items. In this case, add the directive in the <LI> tag. Set the value of the tag as the variable-name. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ESCAPE - Bill Evaluation</title>
<script src="angular.min.js"></script>
</head>
<body>
<h1>ESCAPE - Bill Evaluation</h1>
<h2>Customers</h2>

<form name="BillEvaluation" method="get" ng-app="billsModule">
    <div ng-controller="BillsController as pay">
        <ul>
            <li ng-repeat="client in pay.customers">{{client}}</li>
        </ul>
    </div>
</form>

<script>
    var appModule = angular.module("billsModule", []);
    appModule.controller("BillsController", present);

    function present() {
        this.customers = ["Joseph", "Patricia", "Anthony", "Valerie", "Cynthia"];
    }
</script>
</body>
</html>

This would produce:

Accessing the Members of an Array

When adding new elements to an array, you can use the ng-repeat directive to see the new list of elements. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="appToys">
    <div ng-controller="ToysController as play">
        <h1>Children Toys Store</h1>
        <p style="font-weight: 600">New Toy: <input type="text" ng-model="play.toyName" />
           <input type="button" value="Add" ng-click="play.add()" /></p>

        <h2>Inventory</h2>
        <ul>
            <li ng-repeat="toy in play.toys">{{toy}}</li>
        </ul>
    </div>

<script>
    var app = angular.module('appToys', []);
    app.controller('ToysController', inventorize);

    function inventorize() {
        this.toys = [ "Mini Point of Sale Station", "Drawing Black Board" ];

        this.toys.push("Kid Ferry Boat");

        this.add = function () {
            this.toys.push(this.toyName);
            this.toyName = '';
        }   
    }
</script>
</body>
</html>

This would produce:

Routine Operations on Arrays

AngularJS Arrays and Combo Boxes

AngularJS makes it easy to fill a combo box with elements from an array. To make this possible, first create a <SELECT> tag and add a single <OPTION> child tag to it. If necessary, which is usually the case, add an ng-model directive to the <SELECT> tag with the appropriate name. Add a ng-repeat directive to the <OPTION> tag as seen above. For the value of the <OPTION> tag, create a {{}} placeholder and include the variable in it. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ESCAPE - Bill Evaluation</title>
<script src="angular.min.js"></script>
</head>
<body>
<h1>ESCAPE - Bill Evaluation</h1>
<h2>Customers</h2>

<form name="BillEvaluation" method="get" ng-app="billsModule">
    <p ng-controller="BillsController as pay">Residence:
        <select>
            <option ng-repeat="area in pay.states">{{area}}</option>
        </select>
    </p>
</form>

<script>
    var appModule = angular.module("billsModule", []);
    appModule.controller("BillsController", present);

    function present() {
        this.customers = ["Joseph", "Patricia", "Anthony", "Valerie", "Cynthia"];
        this.states = ['DC', "MD", 'PA', "VA", 'WV'];
    }
</script>
</body>
</html>

Practical LearningPractical Learning: Introducing Arrays and Combo Boxes

  1. Access the BillPreparation.js document and change it as follows:
    var billModule = angular.module('appCableCompany', []);
    billModule.controller("BillsController", function () {
        this.tvPackages = [ 'Basic', 'Standard', 'Performance'];
    
        this.estimate = function () {
            var packageType = this.PackageType;
            var packageFee = 0.00;
            var dvr = Number(this.DVRService || 0);
            var sport = Number(this.SportsPackage || 0);
    
            if (packageType == 'Standard') {
                packageFee = 34.50;
            }
            else if (packageType == 'Performance') {
                packageFee = 51.85;
            }
            else { // Basic
                packageFee = 29.25;
            }
    
            var subTotal = packageFee + dvr + sport;
            var fcc = subTotal * 0.00250881;
            var local = (subTotal + fcc) * 0.0372668;
            var state = (subTotal + fcc) * 0.0082493;
    
            this.fccFee = fcc;
            this.DVRService = dvr;
            this.countyTaxes = local;
            this.stateTaxes = state;
            this.subTotal = subTotal;
            this.SportsPackage = sport;
            this.CableTVPackageFee = packageFee;
            this.paymentAmount = subTotal + fcc + local + state;
        }
    });
  2. Acccess the BillEvaluation.cshtml document and change it as follows:
    @{
        ViewBag.Title = "Bill Evaluation";
    }
    
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/BillPreparation.js"></script>
    <link href="~/Content/CableCompany.css" rel="stylesheet" />
    
    <h1 class="text-center main-title bold">Eastern Shore Company and Production Entertainment</h1>
    <h2 class="text-center main-title bold">Bill Evaluation</h2>
    
    <form name="BillEvaluation" method="post" ng-app="appCableCompany">
        <fieldset ng-controller="BillsController as pay">
            <legend>Cable TV Services</legend>
    
            <div class="row">
                <div class="col-md-6">
                    <div class="bold">Cable TV Package Type</div>
                    <div>
                        <label for="PackageType" style="width: 120px">Package Type:</label>
                        <select id="PackageType" ng-model="pay.PackageType" ng-change="pay.estimate()">
                            <option ng-repeat="pType in pay.tvPackages">{{pType}}</option>
                        </select>
                    </div>
                    <div>
                        <label for="DVRService">DVR Service:</label>
                        <input type="number" id="DVRService" ng-model="pay.DVRService" ng-change="pay.estimate()" />
                    </div>
                    <div>
                        <label for="SportsPackage">Sports Package:</label>
                        <input type="number" id="SportsPackage" ng-model="pay.SportsPackage" ng-change="pay.estimate()" />
                    </div>
                </div>
                <div class="col-md-6">
                    <div>
                        <span class="caption bold">Package Fee:</span>
                        <span class="resulting-value">{{pay.CableTVPackageFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Sub-Total:</span>
                        <span class="resulting-value">{{pay.subTotal.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">FCC Fee:</span>
                        <span class="resulting-value">{{pay.fccFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">County Taxes:</span>
                        <span class="resulting-value">{{pay.countyTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">State Taxes:</span>
                        <span class="resulting-value">{{pay.stateTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Payment Amount:</span>
                        <span class="resulting-value">{{pay.paymentAmount | number:2}}</span>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
  3. To execute the project, press Ctrl + F5

  4. In the DVR Service text box, type 3.98
  5. In the Sports Package, type 9.34
  6. In the Package Type combo box, select Performance:

    Video Collection

  7. Close the browser and return to your programming environment

AngularJS Arrays and Functions

Introduction

We have already seen how to create an array in the constructor of a controller. In the same way, you can create an array in a nested function. The steps are the same. You can start with an empty array. Here is an example:

var appModule = angular.module("comicsModule", []);
    appModule.controller("cyborgController", present);

    function present() {
        this.describe = function () {
            var characteristics = [];
        }
    }

You can also create an array with elements. In both cases, to add a new element to an array, you can call its push() method.

Returning an Array

In the constructor of a controller, you can create a function that produces an array. To do this, create an array in the function, assign it to a local variable, and return that variable before the closing curly bracket of the function. Here is an example:

var appModule = angular.module("comicsModule", []);
    appModule.controller("cyborgController", present);

    function present() {
        this.create = function () {
            var characteristics = [];

            characteristics.push("Super Strength");
            characteristics.push("Advanced Technology");
            characteristics.push("Instant Weaponry");
            characteristics.push("Genius-Level Intellect");
            characteristics.push("Computer Hacking");
            characteristics.push("Teleportation");

            return characteristics;
        }
    }

To access the returning array inside the constructor of the controller, you can call the nested function and assign it to a local variable. Here is an example:

var appModule = angular.module("comicsModule", []);
    appModule.controller("cyborgController", present);

    function present() {
        this.create = function () {
            var characteristics = [ "Super Strength", "Advanced Technology",
                                    "Instant Weaponry", "Genius-Level Intellect",
                                    "Computer Hacking", "Teleportation" ];

            return characteristics;
        }

        this.callers = this.describe();
    }

In the webpage, to get the array returned by the function, you can call it on an instance of the controller. Here is an example:

<!DOCTYPE html>
<html ng-app="comicsModule">
<head>
<meta charset="utf-8" />
<title>DC Comics - Cyborg</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<h1>DC Comics - Cyborg</h1>

<div ng-controller="cyborgController as behave">
        <p>{{behave.create()}}</p>
</div>

<script>
    var appModule = angular.module("comicsModule", []);
    appModule.controller("cyborgController", present);

    function present() {
        this.create = function () {
            var characteristics = [];

            characteristics.push("Teleportation");
            characteristics.push("Super Strength");
            characteristics.push("Instant Weaponry");
            characteristics.push("Computer Hacking");
            characteristics.push("Advanced Technology");
            characteristics.push("Genius-Level Intellect");


            return characteristics;
        }
    }
</script>
</body>
</html>

This technique produces the whole array as one object:

Returning an Array

To access the elements of the array one at a time, use the ng-repeat directive when calling the function. Here is an example:

<!DOCTYPE html>
<html ng-app="comicsModule">
<head>
<meta charset="utf-8" />
<title>DC Comics - Cyborg</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<h1>DC Comics - Cyborg</h1>
<h2>Characteristics</h2>

<div ng-controller="cyborgController as behave">
    <ul>
        <li ng-repeat="one in behave.create()">{{one}}</li>
    </ul>
        
</div>

<script>
    var appModule = angular.module("comicsModule", []);
    appModule.controller("cyborgController", present);

    function present() {
        this.create = function () {
            var characteristics = [];

            characteristics.push("Teleportation");
            characteristics.push("Super Strength");
            characteristics.push("Instant Weaponry");
            characteristics.push("Computer Hacking");
            characteristics.push("Advanced Technology");
            characteristics.push("Genius-Level Intellect");

            return characteristics;
        }
    }
</script>
</body>
</html>

This would produce:

Accessing the Members of the Array

An Array as Argument

As we saw in JavaScript, you can create a function that uses a parameter that is an array. When creating the function, simply provide a name for the parameter. Here is an exampe:

function (lines) {

}

In the body of the function, treat the parameter as an array. Here is an example:

var appModule = angular.module("quotesModule", []);
appModule.controller("QuotesController", present);

this.resume = function (lines) {
    var result = &quot;&quot;;

    for (var section in lines) {
        result += lines[section] + &quot; &quot;;
    }

    return result;
}

When calling the function, if you don't have the value(s) for the argument, pass it as empty square brackets. Here are examples:

var appModule = angular.module("quotesModule", []);
appModule.controller("QuotesController", present);

function present() {
        this.resume = function (lines) {
            var result = "";

            for (var section in lines) {
                result += lines[section] + " ";
            }

            return result;
        }

        resume([]);
}

In this case, if you try to present the array, you would get an undefined result. Therefore when calling the function, if you have a ready array, pass it as argument. Here is an example:

<!DOCTYPE html>
<html ng-app="quotesModule">
<head>
<meta charset="utf-8" />
<title>Movies Quotes</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<h1>Movies Quotes</h1>
<h2>Bordertown</h2>

<div ng-controller="QuotesController as monologue">
    <p>{{monologue.say}}</p>
</div>

<script>
    var appModule = angular.module("quotesModule", []);
    appModule.controller("QuotesController", present);

    function present() {
        this.resume = function (lines) {
            var result = "";

            for (var section in lines) {
                result += lines[section] + " ";
            }

            return result;
        }

        var citations = [ "The days of investigative reporting are over, Lauren.",
                          "The news isn't news anymore.",
                          "It's as dead as the typewriter I used to write it on.",
                          "Corporate America is running the show now.",
                          "And their news agenda is free trade, globalisation and entertainment.",
                          "That's our glorious future.",
                          "-- Bordertown--" ];

        this.say = this.resume(citations);
    }
</script>
</body>
</html>

This would produce:

Angular Functions

The Parameter of a Constructor as an Array

So far, we learned that the second argument of the angular.controller() method is a function. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
.bold     { font-weight: 600; }
.itemName { width: 300px; }
</style>
<title>Department Store</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<script type="text/javascript">
    var app = angular.module("appDepartmentStore", []);
    app.controller("StoreItemsController", prepareInventory);

    function prepareInventory() {
        function getDiscountRate(days) {
            var discountRate = 0.00;

            if (days > 70.00)
                discountRate = 70.00;
            else if (days > 50.00)
                discountRate = 50.00;
            else if (days > 30.00)
                discountRate = 35.00;
            else if (days > 15.00)
                discountRate = 15.00;
            else
                discountRate = 0.00;
            
            return discountRate;
        }

        function calculateMarkedPrice(price, rate) {
            var markedPrice = 0.00;

            if (rate == 0.00)
                markedPrice = 0.00;
            else
                markedPrice = price * rate / 100.00;

            return markedPrice;
        }

        this.calculate = function () {
            var originalPrice = Number(this.inventoryPrice || 0);
            var timeDisplayed = Number(this.daysInStore || 0);

            var discPercentage = getDiscountRate(timeDisplayed);
            var discount = calculateMarkedPrice(originalPrice, discPercentage);

            this.discountRate = discPercentage;
            this.discountAmount = discount;
            this.markedPrice = originalPrice - discount;
        }
    }
</script>

<h1>Department Store</h1>
<h2>Item Price Evaluation</h2>

<form name="DepartmentStore" method="post" ng-app="appDepartmentStore">
    <table ng-controller="StoreItemsController as sic">
        <tr>
            <td class="bold itemName">Item Name:</td>
            <td><input type="text" name="itemName" /></td>
        </tr>
        <tr>
            <td class="bold">Inventory Price:</td>
            <td><input type="text" ng-model="sic.inventoryPrice" ng-change="sic.calculate()" /></td>
        </tr>
        <tr>
            <td class="bold">Days in Store:</td>
            <td><input type="text" ng-model="sic.daysInStore" ng-change="sic.calculate()" /></td>
        </tr>
        <tr>
            <td class="bold">Discount Rate:</td>
            <td>{{sic.discountRate | number : 0}}</td>
        </tr>
        <tr>
            <td class="bold">Discount Amount:</td>
            <td>{{sic.discountAmount | number : 2}}</td>
        </tr>
        <tr>
            <td class="bold">New Marked Price:</td>
            <td>{{sic.markedPrice | number : 2}}</td>
        </tr>
    </table>
</form>
</body>
</html>

Here is an example of using the webpage:

Accessing the Members of the Array

Accessing the Members of the Array

Accessing the Members of the Array

Accessing the Members of the Array

Accessing the Members of the Array

Actually, the second argument can be passed as an array. In this case, if you are passing only the name of the function, you can include it in square brackets. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
.bold     { font-weight: 600; }
.itemName { width: 300px; }
</style>
<title>Department Store</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<script type="text/javascript">
    var app = angular.module("appDepartmentStore", []);
    app.controller("StoreItemsController", [prepareInventory]);

    function prepareInventory() {
        . . . No Change
    }
</script>

<h1>Department Store</h1>
<h2>Item Price Evaluation</h2>

<form name="DepartmentStore" method="post" ng-app="appDepartmentStore">
    <table ng-controller="StoreItemsController as sic">
       . . . No Change
    </table>
</form>
</body>
</html>

We also learned that we can define the constructor directly in the placehoolder of the second argument of the controller. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
.bold     { font-weight: 600; }
.itemName { width: 300px; }
</style>
<title>Department Store</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<script type="text/javascript">
    var app = angular.module("appDepartmentStore", []);
    app.controller("StoreItemsController", function () {

        . . . No Change

    });
</script>

<h1>Department Store</h1>
<h2>Item Price Evaluation</h2>

<form name="DepartmentStore" method="post" ng-app="appDepartmentStore">
    <table ng-controller="StoreItemsController as sic">
        . . . No Change
    </table>
</form>
</body>
</html>

You can include the function of the second argument in square brackets. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
.bold     { font-weight: 600; }
.itemName { width: 300px; }
</style>
<title>Department Store</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<script type="text/javascript">
    var app = angular.module("appDepartmentStore", []);
    app.controller("StoreItemsController", [function () {
        function getDiscountRate(days) {
            var discountRate = 0.00;

            if (days > 70.00)
                discountRate = 70.00;
            else if (days > 50.00)
                discountRate = 50.00;
            else if (days > 30.00)
                discountRate = 35.00;
            else if (days > 15.00)
                discountRate = 15.00;
            else
                discountRate = 0.00;
            
            return discountRate;
        }

        function calculateMarkedPrice(price, rate) {
            var markedPrice = 0.00;

            if (rate == 0.00)
                markedPrice = 0.00;
            else
                markedPrice = price * rate / 100.00;

            return markedPrice;
        }

        this.calculate = function () {
            var originalPrice = Number(this.inventoryPrice || 0);
            var timeDisplayed = Number(this.daysInStore || 0);

            var discPercentage = getDiscountRate(timeDisplayed);
            var discount = calculateMarkedPrice(originalPrice, discPercentage);

            this.discountRate = discPercentage;
            this.discountAmount = discount;
            this.markedPrice = originalPrice - discount;
        }
    }]);
</script>

<h1>Department Store</h1>
<h2>Item Price Evaluation</h2>

<form name="DepartmentStore" method="post" ng-app="appDepartmentStore">
    <table ng-controller="StoreItemsController as sic">

        . . . No Change

    </table>
</form>
</body>
</html>

Using Various Modules in a Web Project

Introduction

In your Web application, you can create and use various modules. You can declare a variable for each module and attach the desired components to it. You can use the same module for different webpages. You can use a different module for each webpage. Of course, each module would have its own component(s). Here are examples.

Web Page: Mathematics.htm

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Central Learning</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<h1>Central Learning</h1>
<div ng-app="methematics">
    <div ng-controller="FormulasController as fc">
        <p>{{fc.description}}</p>
    </div>
    <div ng-controller="CircleController as cc">
        <p>{{cc.area}}</p>
    </div>
</div>

<script type="text/javascript">
    var math = angular.module('methematics', []).controller('FormulasController', function () {
        this.description = "This section contains various formulas used in routine math operations.";
    });

    math.controller('CircleController', function () {
        this.area = "radius * radius * PI";
    });
</script>
</body>
</html>

Web Page: Normalization.htm

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Central Learning</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<h1>Central Learning</h1>

<div ng-app="databases">
    <div ng-controller="NormalizationController as nc">
        <p>{{nc.normalization}}</p>
    </div>
</div>

<script type="text/javascript">
    angular.module('databases', []).controller('NormalizationController', function () {
        this.normalization = "Normalization is important to reduce redundancy.";
    });
</script>
</body>
</html>

A Dependent Module

To conduct its operations, or to assist its component(s), one module A may need operations from another module B. In this case, module A is said to depend on module B. To apply this scenario, you must first create the dependent module.

Remember that, to create a module, you call the module() method of the angular object. The second argument of that method is an array. When creating a module A, to indicate that it depends on another module A, in the square brackets of the second argument of the depending module, enter the name of the first module as a string. Here is an example:

angular.module('methematics', []).
    controller('FormulasController', function () {
            
    });

angular.module('databases', ['methematics']).controller('NormalizationController', function () {

});

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2018-2022, FunctionX Next