Fundamentals of Services and Arrays

Introduction to this Array

As seen in previous lessons, AngularJS provides various techniques to let you create a service. One options it to call the service() method. Here is an example:

var appPayroll = angular.module('appPayroll', []);

function evaluate() {

}

appPayroll.service('payrollService', evaluate);

function summarize(payrollService) {

}

appPayroll.controller('PayrollController', summarize);

In the constructor of a service, you can create the necessary members (properties, methods, etc).

Practical LearningPractical Learning: Introducing Services and 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 PayrollPreparation4
  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 PayrollPreparation 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
  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 -> Style Sheet
  11. Change the file Name to PayrollPreparation
  12. Click Add
  13. Change the document as follows:
    body {
        background-color: white;
    }
    
    .left-column  { width:       150px; }
    .bold         { font-weight: 600;   }
    .ng-model     { width:       100px; }
    .large-text   { width:       120px; }
    .pay-contents { margin:      auto;
                    width:       320px; }
    .common-font  { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  14. In the Solution Explorer, right-click Scripts -> Add -> New Item...
  15. In the left frame of the Add New Item dialog box, click Web and, in the middle frame, click JavaScript File
  16. Change the Name of the file to TimeSheetService
  17. Click Add
  18. Change the document as follows:
    function calculateSalary() {
    
    }
    
    appPayroll.service("timeSheetService", calculateSalary);
  19. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File.
  20. Type PayCheckService as the name of the file
  21. Click OK
  22. In the empty document, type the following code:
    function evaluateTaxes() {
    
    }
    
    appPayroll.service('PayCheckService', evaluateTaxes);
  23. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  24. Type PayrollService
  25. Click Add
  26. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  27. Type PayrollController as the name of the file
  28. Click OK
  29. Type the following code:
    var appPayroll = angular.module("appPayroll", []);
    
    function processPayroll(timeSheetService, payrollService) {
    
    }
    
    appPayroll.controller("PayrollController", processPayroll);
  30. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  31. Change the document as follows:
    using System.Web.Optimization;
    
    namespace PayrollPreparation4
    {
        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/PayrollController.js",
                            "~/Scripts/TimeSheetService.js",
                            "~/Scripts/PayCheckService.js",
                            "~/Scripts/PayrollService.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/PayrollPreparation.css"));
            }
        }
    }

Adding an Array to a Service

To let a property of a service hold many values, you can create it as an array. To do this, create an array in the constructor of the service. Here is an example:

function evaluate() {
    this.filingStatus = [ 'Single', 'Married' ];
}

appPayroll.service('payrollService', evaluate);

Accessing a Service-Based Array

After creating an array in a service, you can send its property to a controller that would get it ready for publishing. Here is an example:

var appPayroll = angular.module('appPayroll', []);

function evaluate() {
    this.filingStatus = [ 'Single', 'Married' ];
}

appPayroll.service('payrollService', evaluate);

function summarize(payrollService) {
    this.preparation = payrollService.filingStatus;
}

appPayroll.controller('PayrollController', summarize);

To access the whole array as an object, use the name of the property defined in the controller. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Payroll Evaluation</title>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/PayrollProcessing.js"></script>
</head>
<body ng-app="appPayroll">
    <div ng-controller="PayrollController as pc">
        <p>Filing Status: {{pc.preparation}}</p>
    </div>
</body>
</html>

Other than that, you can create and use arrays as we saw previously. The steps are just the same.

Practical LearningPractical Learning: Adding an Array to a Service

  1. Click the PayrollService.js tab to access the JavaScript file
  2. In the empty document, type the following code:
    function calculate() {
        this.taxFilingsStatus = [ 'Single', 'Married' ];
    
        var taxableSalary = 0.00;
        var allowanceRate = 77.90;
        
        this.withheldAllowances = function (exmpt) { return allowanceRate * exmpt; }
        this.taxedAmount = function (sal, exmpt) { return sal - (allowanceRate * exmpt); };
    
        this.taxesBasedOnStatus = function (sal, status, exmpt) {
            var withheldAmount = 0;
            var taxableSalary = sal - (allowanceRate * exmpt);
    
            switch (status) {
                case 'Single':
                    if (taxableSalary <= 44) {
                        withheldAmount = 0;
                    }
                    else if ((taxableSalary > 44) && (taxableSalary <= 224)) {
                        withheldAmount = (taxableSalary - 44) * 10 / 100;
                    }
                    else if ((taxableSalary > 224) && (taxableSalary <= 774)) {
                        withheldAmount = 18.00 + ((taxableSalary - 224) * 15 / 100);
                    }
                    else if ((taxableSalary > 774) && (taxableSalary <= 1812)) {
                        withheldAmount = 100.50 + ((taxableSalary - 774) * 25 / 100);
                    }
                    else if ((taxableSalary > 1812) && (taxableSalary <= 3730)) {
                        withheldAmount = 360.00 + ((taxableSalary - 1812) * 28 / 100);
                    }
                    else if ((taxableSalary > 3730) && (taxableSalary <= 8058)) {
                        withheldAmount = 897.04 + ((taxableSalary - 3730) * 33 / 100);
                    }
                    else if ((taxableSalary > 8058) && (taxableSalary <= 8090)) {
                        withheldAmount = 2325.28 + ((taxableSalary - 8058) * 35 / 100);
                    }
                    else { // if (taxableSalary > 8090)
                        withheldAmount = 2336.48 + ((taxableSalary - 8090) * 39.60 / 100);
                    }
    
                    break;
    
                case 'Married':
                    if (taxableSalary <= 166) {
                        withheldAmount = 0;
                    }
                    else if ((taxableSalary > 166) && (taxableSalary <= 525)) {
                        withheldAmount = (taxableSalary - 166) * 10 / 100;
                    }
                    else if ((taxableSalary > 525) && (taxableSalary <= 1626)) {
                        withheldAmount = 35.90 + ((taxableSalary - 525) * 15 / 100);
                    }
                    else if ((taxableSalary > 1626) && (taxableSalary <= 3111)) {
                        withheldAmount = 201.05 + ((taxableSalary - 1626) * 25 / 100);
                    }
                    else if ((taxableSalary > 3111) && (taxableSalary <= 4654)) {
                        withheldAmount = 572.30 + ((taxableSalary - 3111) * 28 / 100);
                    }
                    else if ((taxableSalary > 4654) && (taxableSalary <= 8180)) {
                        withheldAmount = 1004.34 + ((taxableSalary - 4654) * 33 / 100);
                    }
                    else if ((taxableSalary > 8160) && (taxableSalary <= 9218)) {
                        withheldAmount = 2167.92 + ((taxableSalary - 8180) * 35 / 100);
                    }
                    else { // if (taxableSalary > 9218)
                        withheldAmount = 2531.22 + ((taxableSalary - 9218) * 39.60 / 100);
                    }
                    break;
    
                default:
                    withheldAmount = 0.00;
                    break;
            }
    
            return withheldAmount;
        }
    }
    
    appPayroll.service('payrollService', calculate);
  3. Click the PayrollController.js tab to access the JavaScript file
  4. Change the document as follows:
    var appPayroll= angular.module("appPayroll", []);
    
    function processPayroll(timeSheetService, payrollService) {
        this.filingStatus = payrollService.taxFilingsStatus;
    
        this.proceed = function () {
            var dependents = Number(this.exemptions || 0);
            var salary = Number(this.grossSalary || 0);
    
            this.allowances = payrollService.withheldAllowances(dependents)
            this.taxableGrossWages = payrollService.taxedAmount(salary, dependents);
            this.federalIncomeTax = payrollService.taxesBasedOnStatus(salary, this.filingsStatus, dependents);
        }
    }
    
    appPayroll.controller("PayrollController", processPayroll);
  5. In the Solution Explorer, expand Controllers and double-click HomeController.cs to access the class
  6. Create a method named TaxWithholdingEvaluation as follows:
    using System.Web.Mvc;
    
    namespace PayrollPreparation4.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 TaxWithholdingEvaluation()
            {
                return View();
            }
        }
    }
  7. In the Solution Explorer, expand Home and expand Shared
  8. Double-click _Layout.cshtml to open the file
  9. 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>Fun Department Store :: @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("Fun Department Store", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Payroll Evaluation", "TaxWithholdingEvaluation", "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 common-font">&copy; @DateTime.Now.Year - Fun Department Store (FDS)</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  10. Click the HomeController.cs tab to access the controller
  11. In the class, right-click TaxWithholdingEvaluation -> Add View...
  12. In the Add View dialog box, make sure the View Name text box is displaying TaxWithholdingEvaluation. Click Add
  13. Change the document as follows:
    @{
        ViewBag.Title = "Tax Withholding Evaluation";
    }
    
    <h1 class="common-font text-center bold">Payroll Preparation</h1>
    <h2 class="common-font text-center">Tax Withholding Evaluation</h2>
    
    @Scripts.Render("~/bundles/jquery")
    
    <div class="pay-contents" ng-app="appPayroll">
        <form name="IncomeTaxPreparation" method="post" ng-controller="PayrollController as pc">
            <table class="table table-striped">
                <tr>
                    <td class="left-col">Gross Salary:</td>
                    <td><input type="number" class="form-control" ng-model="pc.grossSalary" ng-change="pc.proceed()" /></td>
                </tr>
                <tr>
                    <td>Filing as:</td>
                    <td>
                        <select class="form-control" ng-model="pc.filingsStatus" ng-change="pc.proceed()">
                            <option ng-repeat="fs in pc.filingStatus">{{fs}}</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Exemptions:</td>
                    <td><input type="number" class="form-control" ng-model="pc.exemptions" ng-change="pc.proceed()" /></td>
                </tr>
                <tr>
                    <td>Allowances:</td>
                    <td>{{pc.allowances | number: 2}}</td>
                </tr>
                <tr>
                    <td>Taxable Gross Wages:</td>
                    <td>{{pc.taxableGrossWages | number: 2}}</td>
                </tr>
                <tr>
                    <td>Federal Income Tax:</td>
                    <td>{{pc.federalIncomeTax | number: 2}}</td>
                </tr>
            </table>
        </form>
    </div>
  14. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Introduction to AngularJS Services

  15. In the Gross Salary text box, type 2516

    Introduction to AngularJS Services

  16. In the Filing As combo box, select Single

    Introduction to AngularJS Services

  17. In the Exemptions text box, type 3

    Introduction to AngularJS Services

  18. Close the browser and return to your programming environment

Factory Services and Arrays

Introduction

A factory service is a service created by calling the factory() method of an angular.module() object. Here is an example:

var appUtilityCompany = angular.module("appUtilities", []);

function manage() {

}
appUtilityCompany.factory("BillsController", manage);

function prepare(BillsController) {

}

appUtilityCompany.controller("GasBillsController", prepare);

Remember that if you want to create a simple service that only produces a constant, you can return that constant from the constructor of the factory service. In the same way, if you want a simple service that only holds an array, return that array from the function. Here is an example:

function manage() {
    return ['Residence', 'Small Business', 'Enterprise'];
}
appUtilityCompany.factory("BillsController", manage);

To access the array in a webpage, assign the name of the service to a property in the constructor of the controller, and access that property in the webpage. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gas Utility Company</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="appUtilities">
    <h1>Gas Utility Company</h1>

    <p ng-controller="BillsController as gbc">Account Types: {{gbc.accountType}}</p>

<script>
    var appUtilityCompany = angular.module("appUtilities", []);

    function manage() {
        return ['Residence', 'Small Business', 'Enterprise'];
    }
    appUtilityCompany.factory("BillsController", manage);

    function prepare(BillsController) {
        this.accountType = BillsController;
    }

    appUtilityCompany.controller("BillsController", prepare);
</script>
</body>
</html>

This would produce:

Factory Services and Arrays

Otherwise, remember that, to benefit from a factory service, create an object in the constructor of the service and return that object. Here is an example:

function manage() {
    var bill = {};

    return bill;
}
appUtilityCompany.factory("BillsController", manage);

After that, you can add the desired members, including one or more arrays, to the object.

Practical LearningPractical Learning: Introducing Factory Services

  1. On the main menu of Microsoft Visual Studio , click File -> New -> Project...
  2. In the middle frame of the New Project dialog box, click ASP.NET Web Application (.NET Framework). Change the project Name to GasUtilityCompany2
  3. Click OK
  4. In the New ASP.NET Web Application dialog box, click the MVC icon and click OK
  5. In the Solution Explorer, right-click GasUtilityCompany2 and click Manage NuGet Packages...
  6. Click the Browser button.
    Do a search on angular
  7. In the list, click angularjs
  8. In the middle-right frame, click Install. If a dialog box comes up, read it and click OK
  9. In the Solution Explorer, right-click Content -> Add -> Style Sheet
  10. Type GasCompany as the name of the file
  11. Click Add
  12. Create some styles as follows:
    body {
        background-color: white;
    }
    
    .bold          { font-weight: 600;    }
    .bill-contents { margin:      auto;
                     width:       325px;  }
    .txtContext    { width:       80px;   }
    .btnFormat     { height:      32px;
                     width:       200px;  }
    .left-column   { width:       195px;  }
    .common-font   { font-family: Georgia, 'Times New Roman', Times, serif; }
  13. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  14. Type BillsController as the name of the file
  15. Click Add
  16. Type the following code in the empty document:
    var appUtilityCompany = angular.module("appGasCompany", []);
    
    function prepare() {
    
    }
    
    appUtilityCompany.controller("BillsController", prepare);
  17. To create a service, in the Solution Explorer, right-click Scripts -> Add -> New Item...
  18. In the left frame of the Add New Item dialog box, click Web and, in the middle frame, click JavaScript File
  19. Change the Name of the file to BillsService
  20. Click Add
  21. In the empty document, type the following code:
    function manage() {
    
    }
    
    appUtilityCompany.factory("billsService", manage);
  22. Access the BillsController.js file and pass the billsService service as parameter to the function:
    var appUtilityCompany = angular.module("appGasCompany", []);
    
    function prepare(billsService) {
    
    }
    
    appUtilityCompany.controller("BillsController", prepare);
  23. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  24. Change the document as follows:
    using System.Web.Optimization;
    
    namespace GasUtilityCompany2
    {
        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/BillsController.js",
                            "~/Scripts/BillsService.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/GasCompany.css"));
            }
        }
    }
  25. In the Solution Explorer, expand Controllers and double-click HomeController.cs
  26. In the class, add a class named BillEvaluation as follows:
    using System.Web.Mvc;
    
    namespace GasUtilityCompany2.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();
            }
        }
    }
  27. In the Solution Explorer, expand Home and expand Shared
  28. Double-click _Layout.cshtml to open the file
  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>Gas Utility Company :: @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("Gas Utility Company", "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="common-font text-center">&copy; @DateTime.Now.Year - Gas Utility Company</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>

Adding an Array to a Factory Service

To get an array in a factory service, you have various options. You can create a method that returns an array. The classic or most common way to get an array is to create a property and assign it an array. Here is an example:

function manage() {
    var bill = {
        category: ['Residence', 'Small Business', 'Enterprise']
    };

    return bill;
}
appUtilityCompany.factory("BillsController", manage);

To access the array in a webpage, use the name of the property. You can use the ng-repeat directive to access each element of the array. Here is an example:

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

<script>
    var appUtilityCompany = angular.module("appGasCompany", []);

    function manage() {
        var bill = {
            category: ['Residence', 'Small Business', 'Enterprise']
        };

        return bill;
    }
    appUtilityCompany.factory("BillsController", manage);

    function prepare(BillsController) {
        this.accountType = BillsController.category;
    }

    appUtilityCompany.controller("BillsController", prepare);
</script>

<div ng-app="appGasCompany" ng-controller="BillsController as gbc">
    <p ng-repeat="cust in gbc.accountType">Account Types: {{cust}}</p>
</div>
</body>
</html>

Practical LearningPractical Learning: Adding an Array to a Service

  1. Access the BillsService.js document and change it as follows:
    function manage() {
        var taxableSalary = 0.00;
        var allowanceRate = 77.90;
    
        var gasBill = {
            accountType: ['Industrial', 'Residential', 'Commercial'],
            consumption: function (a, b) { return b - a; },
    
            therms: function (a, b) { return gasBill.consumption(a, b) * 1.0367; },
            adjust: function (a, b) { return gasBill.therms(a, b) * 0.13086; },
            carrying: function (a, b) {
                var thrm = gasBill.therms(a, b);
    
                if (thrm <= 5000)
                    return thrm * 0.016289;
                else
                    return thrm * 0.009577;
            },
            deliv: function (a, b, c) {
                var thrm = gasBill.therms(a, b);
                var trans = gasBill.carrying(a, b);
                var first50Therms = 0, over50Therms = 0;
    
                if (thrm < 5000) {
                    first50Therms = thrm * 0.05269;
                    over50Therms = 0;
                }
                else {
                    first50Therms = 5000 * 0.5269;
                    over50Therms = (thrm - 5000) * 0.04995;
                }
    
                var subTotal = trans + gasBill.adjust(a, b) + first50Therms + over50Therms;
    
                if (c == 'Commercial')
                    return subTotal + 34.05;
                else if (c == 'Industrial')
                    return subTotal + 26.68;
                else // if (c == 'Residential')
                    return subTotal + 17.84;
            },
            enviro: function (a, b, c) { return gasBill.deliv(a, b, c) * 0.0045; },
            pmt: function (a, b, c) { return gasBill.deliv(a, b, c) + gasBill.enviro(a, b, c); }
        };
    
        return gasBill;
    }
    
    appGasCompany.factory('billsService', manage);
  2. Access the BillsController.js document and change it as follows:
    var appGasCompany = angular.module("appGasCompany", []);
    
    function prepare(billsService) {
        this.filingStatus = billsService.accountType;
    
        this.proceed = function () {
            var readingBeginning = Number(this.counterReadingStart || 0);
            var readingEnd = Number(this.counterReadingEnd || 0);
    
            this.CCFTotal              = billsService.consumption(readingBeginning, readingEnd);
            this.totalTherms           = billsService.therms(readingBeginning, readingEnd);
            this.ditributionAdjustment = billsService.adjust(readingBeginning, readingEnd);
            this.transportationCharges = billsService.carrying(readingBeginning, readingEnd);
            this.totalDelivery         = billsService.deliv(readingBeginning, readingEnd, this.filingsStatus);
            this.environmentCharges    = billsService.enviro(readingBeginning, readingEnd, this.filingsStatus);
            this.amountDue             = billsService.pmt(readingBeginning, readingEnd, this.filingsStatus);
        }
    }
    
    appGasCompany.controller("BillsController", prepare);
  3. Click the HomeController.cs tab to access the controller
  4. In the class, right-click BillEvaluation and click Add View...
  5. Make sure the View Name text box is displaying BillEvaluation. Click Add
  6. Change the document as follows:
    @{
        ViewBag.Title = "Bill Evaluation";
    }
    
    <h1 class="common-font text-center bold">Gas Utility Company</h1>
    <h2 class="common-font text-center bold">Bill Evaluation</h2>
    
    @Scripts.Render("~/bundles/jquery")
    
    <div class="bill-contents" ng-app="appGasCompany">
        <form name="IncomeTaxPreparation" method="post" ng-controller="BillsController as pc">
            <table class="table table-condensed">
                <tr>
                    <td><label for="CounterReadingEnd" class="bold">Counter Reading End:</label></td>
                    <td>
                        <input type="text" id="CounterReadingEnd" class="form-control txtContext"
                               ng-model="pc.counterReadingEnd" ng-change="pc.proceed()" />
                    </td>
                </tr>
                <tr>
                    <td class="left-column bold"><label for="CounterReadingStart">Counter Reading Start:</label></td>
                    <td>
                        <input type="text" id="CounterReadingStart" class="form-control txtContext"
                               ng-model="pc.counterReadingStart" ng-change="pc.proceed()" />
                    </td>
                </tr>
                <tr>
                    <td><label for="FilingStatus" class="bold">Account Type:</label></td>
                    <td>
                        <select class="form-control" id="FilingStatus" ng-model="pc.filingsStatus" ng-change="pc.proceed()">
                            <option ng-repeat="fs in pc.filingStatus">{{fs}}</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td class="bold">CCF Total:</td>
                    <td>{{pc.CCFTotal}}</td>
                </tr>
                <tr>
                    <td class="bold">Total Therms:</td>
                    <td>{{pc.totalTherms | number: 2}}</td>
                </tr>
                <tr>
                    <td class="bold">Ditribution Adjustment:</td>
                    <td>{{pc.ditributionAdjustment | number: 2}}</td>
                </tr>
                <tr>
                    <td class="bold">Transportation Charges:</td>
                    <td>{{pc.transportationCharges | number: 2}}</td>
                </tr>
                <tr>
                    <td class="bold">Total Delivery:</td>
                    <td>{{pc.totalDelivery | number: 2}}</td>
                </tr>
                <tr>
                    <td class="bold">Environment Charges:</td>
                    <td>{{pc.environmentCharges | number: 2}}</td>
                </tr>
                <tr>
                    <td class="left-column bold">Amount Due:</td>
                    <td>{{pc.amountDue | number: 2}}</td>
                </tr>
            </table>
        </form>
    </div>
  7. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Adding an Array to a Service

  8. In the Counter Reading End text box, type 216079

    Adding an Array to a Service

  9. In the Counter Reading Start text box, type 214485

    Adding an Array to a Service

  10. In the Account Type combo box, select Industrial

    Adding an Array to a Service

  11. In the Account Type combo box, select Residential

    Adding an Array to a Service

  12. In the Account Type combo box, select Commercial

    Adding an Array to a Service

  13. Close the form and return to your programming environment

Introduction to Scoping an Array

When creating a constructor that uses the $scope service, you may want the object to use an array. In this case, you can attach the array to the scope object. To do this, you can attach a property to the scope and assign an array to it. Other than that, the array is created and used as wie saw previously.

Practical LearningPractical Learning: Scoping an Array

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the New Project dialog box, click ASP.NET Web Application (.NET Framework).
    Change the project Name to ChairExecs1
  3. Click OK
  4. In the New ASP.NET Web Application dialog box, click the MVC icon and click OK
  5. In the Solution Explorer, right-click ChairExecs1 and click Manage NuGet Packages...
  6. Click the Browser button.
    Do a search on AngularJS (you must be connected to the Internet)
  7. In the list, click angularjs
  8. In the middle-right frame, click Install. If a dialog box comes up, read it and click OK
  9. To create a new CSS file, in the Solution Explorer, right-click Content -> Add -> Style Sheet
  10. Change the file Name to ChairExecs
  11. Click Add
  12. Change the document as follows:
    body {
        background-color: white;
    }
    
    .bold           { font-weight:   600;   }
    .large          { width:         375px; }
    .medium         { width:         150px; }
    .small          { width:         75px;  }
    .xsmall         { width:         55px;  }
    .order-contents { margin:        auto;
                      width:         650px; }
    .heading        { font-size:     14px;
                      border-bottom: 2px double black; }
    .common-font    { font-family:   Georgia, Garamond, 'Times New Roman', serif; }
  13. In the Solution, right-click Scripts -> Add -> JavaScript File
  14. Type ChairExecs as the name of the file
  15. Click OK
  16. Change the document as follows:
    var appBusiness = angular.module("appChairExecs", []);
    
    function prepare($scope) {
        $scope.basics     = [ "Station", "Essential", "Instructor" ];
        $scope.selectives = [ "Scholar", "Director" ];
        $scope.executives = [ "Excel Extent", "Executive" ];
    
        $scope.evaluate = function () {
            var firstSelection  = $scope.type1Name;
            var secondSelection = $scope.type2Name;
            var thirdSelection  = $scope.type3Name;
            var weight1 = 0, weight2 = 0, weight3 = 0;
            var quantity1 = 0, quantity2 = 0, quantity3 = 0;
            var subTotal1 = 0, subTotal2 = 0.00, subTotal3 = 0.00;
            var totalWeight1 = 0, totalWeight2 = 0, totalWeight3 = 0;
            var selection1Price = 0.00, selection2Price = 0.00, selection3Price = 0.00;
    
            if (firstSelection == "Station") {
                weight1 = 28;
                selection1Price = 42.45;
            }
            else if (firstSelection == "Essential") {
                weight1 = 32;
                selection1Price = 54.67;
            }
            else if (firstSelection == "Instructor") {
                weight1 = 36;
                selection1Price = 68.93;
            }
            else { // No selection made in the combo box
                weight1 = 0;
                selection1Price = 0.00;
            }
    
            if (secondSelection == "Scholar") {
                weight2 = 36;
                selection2Price = 88.65;
            }
            else if (secondSelection == "Director") {
                weight2 = 38;
                selection2Price = 104.25;
            }
            else {
                weight2 = 0;
                selection2Price = 0.00;
            }
    
            if (thirdSelection == "Excel Extent") {
                weight3 = 66;
                selection3Price = 128.74;
            }
            else if (thirdSelection == "Executive") {
                weight3 = 78;
                selection3Price = 174.36;
            }
            else {
                weight3 = 0;
                selection3Price = 0.00;
            }
    
            quantity1 = Number($scope.type1Quantity || 0);
            quantity2 = Number($scope.type2Quantity || 0);
            quantity3 = Number($scope.type3Quantity || 0);
    
            totalWeight1 = weight1 * quantity1;
            totalWeight2 = weight2 * quantity2;
            totalWeight3 = weight3 * quantity3;
    
            subTotal1 = selection1Price * quantity1;
            subTotal2 = selection2Price * quantity2;
            subTotal3 = selection3Price * quantity3;
    
            $scope.type1UnitWeight = weight1;
            $scope.type1UnitPrice = selection1Price;
    
            $scope.type2UnitWeight = weight2;
            $scope.type2UnitPrice = selection2Price;
    
            $scope.type3UnitWeight = weight3;
            $scope.type3UnitPrice = selection3Price;
    
            if (quantity1 != 0) {
                $scope.type1TotalWeight = totalWeight1;
                $scope.type1SubTotal = subTotal1;
            }
            else {
                $scope.type1TotalWeight = "";
                $scope.type1SubTotal = "";
            }
    
            if (quantity2 != 0) {
                $scope.type2TotalWeight = totalWeight2;
                $scope.type2SubTotal = subTotal2;
            }
            else {
                $scope.type2TotalWeight = "";
                $scope.type2SubTotal = "";
            }
    
            if (quantity3 != 0) {
                $scope.type3TotalWeight = totalWeight3;
                $scope.type3SubTotal = subTotal3;
            }
            else {
                $scope.type3TotalWeight = "";
                $scope.type3SubTotal = "";
            }
    
            var shipping = 0.00;
            var discRate = 0.00;
            var totalPrices = subTotal1 + subTotal2 + subTotal3;
            var totalWeight = totalWeight1 + totalWeight2 + totalWeight3;;
    
            if (totalPrices >= 800)
            {
                discRate = 20; // %
            }
            else if (totalPrices >= 600)
            {
                discRate = 15; // %
            }
            else if (totalPrices >= 300)
            {
                discRate = 10; // %
            }
            else
            {
                discRate = 0; // %
            }
    
            if (totalWeight >= 200)
            {
                shipping = 42.50;
            }
            else if (totalWeight >= 150)
            {
                shipping = 36.25;
            }
            else if (totalWeight >= 100)
            {
                shipping = 24.48;
            }
            else if (totalWeight >= 50)
            {
                shipping = 18.65;
            }
            else
            {
                shipping = 12.25;
            }
    
            var discAmt = totalPrices * discRate / 100;
    
            $scope.totalWeight = totalWeight;
            $scope.subTotal = totalPrices;
            $scope.discountRate = discRate;
            $scope.discountAmount = discAmt;
            $scope.shippingAndHandling = shipping;
            $scope.orderTotal = totalPrices - discAmt + shipping;
        }
    }
    
    appBusiness.controller("CustomerOrderController", prepare);
  17. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  18. Change the document as follows:
    using System.Web.Optimization;
    
    namespace ChairExecs1
    {
        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/ChairExecs.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/ChairExecs.css"));
            }
        }
    }
  19. In the Solution Explorer, expand Controllers and double-click HomeController.cs
  20. In the class, add a class named BillEvaluation as follows:
    using System.Web.Mvc;
    
    namespace ChairExecs1.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 CustomerOrderEvaluation()
            {
                return View();
            }
        }
    }
  21. In the Solution Explorer, expand Home and expand Shared
  22. Double-click _Layout.cshtml to open the file
  23. 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>Chair Executives :: @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("Chair Executives", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Customer Order Evaluation", "CustomerOrderEvaluation", "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="common-font text-center">&copy; @DateTime.Now.Year - Chair Executives</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  24. Click the HomeController.cs tab
  25. In the document, right-click CustomerOrderEvaluation() -> Add View...
  26. Make sure the View Name text box displays CustomerOrderEvaluation.
    . Click Add
  27. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <link href="Content/ChairExecs.css" rel="stylesheet" />
    <title>Chair Executives - Customer Order Evaluation</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/ChairExecs.js"></script>
    </head>
    <body>
    <div class="order-contents" ng-app="appChairExecs">
        <h2 class="common-font bold text-center">Customer Order Evaluation</h2>
    </body>
    </html>
  28. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Scoping an Array

  29. In the first combo box, select Essential

    Introduction to Scoping an Array

  30. In the top Quantity text box, type 6

    Introduction to Scoping an Array

  31. In the second combo box, select Director
  32. In the second text box below Quantity, type 2

    Introduction to Scoping an Array

  33. In the third combo box, select Excel Extent
  34. In the third text box below Quantity, type 8

    Introduction to Scoping an Array

  35. Close the browser and return to your programming environment

Factory Services and Arrays

To get an array in a factory service, you have various options. You can create a method that returns an array. The classic or most common way to get an array is to create a property and assign it an array. Here is an example:

function manage() {
    var bill = {
        category: ['Residence', 'Small Business', 'Enterprise']
    };

      return bill;
}
appUtilityCompany.factory("BillsController", manage);

To access the array in a webpage, use the name of the property. You can use the ng-repeat directive to access each element of the array. Here is an example:

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

<script>
    var appUtilityCompany = angular.module("appGasCompany", []);

    function manage() {
        var bill = {
            category: ['Residence', 'Small Business', 'Enterprise']
        };

        return bill;
    }
    appUtilityCompany.factory("BillsController", manage);

    function prepare(BillsController) {
        this.accountType = BillsController.category;
    }

    appUtilityCompany.controller("BillsController", prepare);
</script>

<div ng-app="appGasCompany" ng-controller="BillsController as gbc">
    <p ng-repeat="cust in gbc.accountType">Account Types: {{cust}}</p>
</div>
</body>
</html>

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2018-2022, FunctionX Next