Introduction to Arrays of Objects

Overview

You can create an array of objects in the body of the constructor of a component. As we saw with JavaScript, if you want to signal an array but don't have elements for it, assign empty square brackets to a scoped variable. Here is an example:

var appBusiness = angular.module("appWaterCompany", []);

function create($scope) {
    $scope.orders = [];
}

appBusiness.controller("CustomersController", ["$scope", create]);

Practical LearningPractical Learning: Introducing Arrays of Objects

  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 ChairExecs2
  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 ChairExecs2 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;   }
    .tbl-order-nbr  { width:         300px; }
    .large          { width:         360px; }
    .medium         { width:         150px; }
    .small          { width:         80px;  }
    .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. In the empty document, type the following code:
    var appBusiness = angular.module("appChairExecs", []);
    
    function prepare($scope) {
        $scope.orders = [];
    }
    
    appBusiness.controller("CustomerOrderController", ['$scope', prepare]);

The Array Object

Once again, remember that when you create an array, including an array of objects, it is automatically of type Array.

Adding Objects to an Array

Specifying the Object of an Index of an Array

As we saw in JavaScript, you can apply the square brackets to the name of the array, pass an index in the square brackets, and assign the desired object.

Practical LearningPractical Learning: Specifying the Object of an Index

Adding a New Object to an Array

To add an object to an array, you can define the object in the square brackets. In the same way, you can add many objects in the square brackets. Here is an example:

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

inventorize.$inject = ['$scope'];

function inventorize($scope) {
    $scope.toys = [{ itemNumber: 937495, toyName: "Mini Point of Sale Station", unitPrice: 32.64 },
                   { itemNumber: 309581, toyName: "Drawing Black Board",        unitPrice: 18.45 }];  
}

An Array of Objects for a Property of an Object

A property of an object can hold an array. To make this possible, create an array and assign it to a named attached to a $scope object. Here is an example:

var app = angular.module("CPARApp", []);
app.controller("CPARController", repair);

function repair($scope) {
    $scope.repairOrder = {
        parts : [ { partName: "Air Filter", price: 8.95 },
                  { partName: "Gasket Intake Manifold", price: 225.67 },
                  { partName: 'Front Wheel Hub Bearing Kit', price: 96.88 },
                  { partName: "Oil Seal", price: 6.34 } ]
    };
}

Pushing an Object to an Array

To let you add an object to an array, we already know that the Array object provides the push() method that you can use. Here are two examples of calling that method:

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

inventorize.$inject = ['$scope'];

function inventorize($scope) {
    $scope.toys = [{ itemNumber: 937495, toyName: "Mini Point of Sale Station", unitPrice: 32.64 },
                   { itemNumber: 309581, toyName: "Drawing Black Board",        unitPrice: 18.45 }];

    $scope.toys.push({ itemNumber: 749374, toyName: "Kid Ferry Boat", unitPrice: 24.86 });

    $scope.add = function () {
        var toy = { itemNumber: $scope.stockNumber, toyName: $scope.name, unitPrice: $scope.price }
        $scope.toys.push(toy);
    }   
}

Accessing the Objects of an Array

Introduction

If you know the index of an object in an array, you can access the object from that index. To do this, pass the index to square brackets applied to name of the array. After the closing square bracket, type a period followed by the desired member of the object.

Practical LearningPractical Learning: Accessing an Element of the Array

  1. Change the ChairExecs.js document as follows:
    var appBusiness = angular.module("appChairExecs", []);
    
    function prepare($scope) {
        $scope.orders = [];
    
        $scope.orders[0] = {
            orderNumber: 100001,
            chair1Name: "Essential", quantity1: 6,
            chair2Name: "Director", quantity2: 2,
            chair3Name: "Excel Extent", quantity3: 8
        };
        $scope.orders[1] = {
            orderNumber: 100002,
            chair1Name: "", quantity1: 0,
            chair2Name: "", quantity2: 0,
            chair3Name: "Executive", quantity3: 1
        };
        $scope.orders[2] = {
            orderNumber: 100003,
            chair1Name: "Instructor", quantity1: 3,
            chair2Name: "Scholar", quantity2: 3,
            chair3Name: "", quantity3: 0
        };
        $scope.orders[3] = {
            orderNumber: 100004,
            chair1Name: "Station", quantity1: 10,
            chair2Name: "Scholar", quantity2: 5,
            chair3Name: "Executive", quantity3: 2
        };
    
        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;
    
        $scope.orderNbr      = $scope.orders[0].orderNumber;
        $scope.type1Name     = $scope.orders[0].chair1Name;
        $scope.type2Name     = $scope.orders[0].chair2Name;
        $scope.type3Name     = $scope.orders[0].chair3Name;
        $scope.type1Quantity = $scope.orders[0].quantity1;
        $scope.type2Quantity = $scope.orders[0].quantity2;
        $scope.type3Quantity = $scope.orders[0].quantity3;
    
        if ($scope.type1Name == "Station") {
            weight1 = 28;
            selection1Price = 42.45;
        }
        else if ($scope.type1Name == "Essential") {
            weight1 = 32;
            selection1Price = 54.67;
        }
        else if ($scope.type1Name == "Instructor") {
            weight1 = 36;
            selection1Price = 68.93;
        }
        else {
            weight1 = 0;
            selection1Price = 0.00;
        }
    
        if ($scope.type2Name == "Scholar") {
            weight2 = 36;
            selection2Price = 88.65;
        }
        else if ($scope.type2Name == "Director") {
            weight2 = 38;
            selection2Price = 104.25;
        }
        else {
            weight2 = 0;
            selection2Price = 0.00;
        }
    
        if ($scope.type3Name == "Excel Extent") {
            weight3 = 66;
            selection3Price = 128.74;
        }
        else if ($scope.type3Name == "Executive") {
            weight3 = 78;
            selection3Price = 174.36;
        }
        else {
            weight3 = 0;
            selection3Price = 0.00;
        }
    
        var quantity1 = Number($scope.type1Quantity || 0);
        var quantity2 = Number($scope.type2Quantity || 0);
        var 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", ['$scope', prepare]);
  2. In the Solution, right-click ChairExecs2 -> Add -> HTML Page
  3. Type CustomerOrderReview as the name of the file
  4. Click OK
  5. 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" />
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/ChairExecs.js"></script>
    <title>Chair Executives - Customer Order Review</title>
    </head>
    <body ng-app="appChairExecs">
        <div class="order-contents" ng-controller="CustomerOrderController">
            <h2 class="common-font bold text-center">Customer Order Review</h2>
    
            <table class="table tbl-order-nbr">
                <tr>
                    <td class="bold">Order #:</td>
                    <td>{{orderNbr}}</td>
                </tr>
            </table>
            <form name="CustomerOrderEvaluation" method="post">
                <table class="table table-striped">
                    <tr>
                        <td class="large heading bold text-center" style="border-right: 3px solid silver">Item Definition</td>
                        <td class="heading bold text-center">Sale Description</td>
                    </tr>
                </table>
                <table class="table table-bordered">
                    <tr>
                        <td class="medium bold">Item Name</td>
                        <td class="bold">Weight(Lbs)</td>
                        <td class="bold">Unit Price</td>
                        <td class="bold">Quantity</td>
                        <td class="bold">Weight(Lbs)</td>
                        <td class="bold">Sub-Total</td>
                    </tr>
                    <tr>
                        <td>{{type1Name}}</td>
                        <td>{{type1UnitWeight}}</td>
                        <td>{{type1UnitPrice | number : 2}}</td>
                        <td>{{type1Quantity}}</td>
                        <td>{{type1TotalWeight}}</td>
                        <td>{{type1SubTotal | number : 2}}</td>
                    </tr>
                    <tr>
                        <td>{{type2Name}}</td>
                        <td>{{type2UnitWeight}}</td>
                        <td>{{type2UnitPrice | number : 2}}</td>
                        <td>{{type2Quantity}}</td>
                        <td>{{type2TotalWeight}}</td>
                        <td>{{type2SubTotal | number : 2}}</td>
                    </tr>
                    <tr>
                        <td>{{type3Name}}</td>
                        <td>{{type3UnitWeight}}</td>
                        <td>{{type3UnitPrice | number : 2}}</td>
                        <td>{{type3Quantity}}</td>
                        <td>{{type3TotalWeight}}</td>
                        <td>{{type3SubTotal | number : 2}}</td>
                    </tr>
                </table>
                <hr />
                <table class="table table-striped">
                    <tr>
                        <td class="medium bold">Total Weight (Lbs):</td>
                        <td>{{totalWeight}}</td>
                        <td style="width: 80px">&nbsp;</td>
                        <td class="bold">Sub-Total:</td>
                        <td>{{subTotal | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Discount Rate (%):</td>
                        <td>{{discountRate}}</td>
                        <td>&nbsp;</td>
                        <td class="bold">Discount Amount:</td>
                        <td>{{discountAmount | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Shipping &amp; Handling:</td>
                        <td>{{shippingAndHandling | number : 2}}</td>
                        <td>&nbsp;</td>
                        <td class="bold">Order Total:</td>
                        <td>{{orderTotal | number : 2}}</td>
                    </tr>
                </table>
            </form>
        </div>
    </body>
    </html>
  6. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Scoping an Array

  7. Close the browser and return to your programming environment

A Repeating Directive for an Array of Objects

We saw that, to support looping, AngularJS provides the ng-repeat directive. When it comes to a table, add an ng-repeat directive to a <TR> tag. Then use its variable-name as the value of the <TD> tag. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
<style>
.container {
    margin: auto;
    width:  380px;
}
.bold { font-weight: 600; }
.small { width: 60px; }
.medium { width: 100px; }
.large { width: 200px; }
.centered { text-align: center }
.tbl-inventory { width: 100%; }
</style>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="appToys">
<div class="container" ng-controller="ToysController">
    <h1 class="centered">Children Toys Store</h1>
    <h2 class="centered">New Toy</h2>
    
    <table>
        <tr>
            <td class="medium bold">Item #</td>
            <td><input type="text" ng-model="stockNumber" /></td>
        </tr>
        <tr>
            <td class="bold">Toy Name:</td>
            <td><input type="text" ng-model="name" /></td>
        </tr>
        <tr>
            <td class="bold">Unit Price:</td>
            <td><input type="text" ng-model="price" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="button" value="Add Toy to Inventory" ng-click="add()" /></td>
        </tr>
    </table>

    <h2 class="centered">Inventory</h2>
        
    <table class="tbl-inventory" border="2">
        <tr class="bold">
            <td class="small">Item #</td>
            <td class="large">Toy Name</td>
            <td>Unit Price</td>
        </tr>
        <tr ng-repeat="toy in toys">
            <td>{{toy.itemNumber}}</td>
            <td>{{toy.toyName}}</td>
            <td>{{toy.unitPrice}}</td>
        </tr>
    </table>
</div>

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

    inventorize.$inject = ['$scope'];

    function inventorize($scope) {
        $scope.toys = [{ itemNumber: 937495, toyName: "Mini Point of Sale Station", unitPrice: 32.64 },
                       { itemNumber: 309581, toyName: "Drawing Black Board",        unitPrice: 18.45 }];

        $scope.toys.push({ itemNumber: 749374, toyName: "Kid Ferry Boat", unitPrice: 24.86 });

        $scope.add = function () {
            var toy = { itemNumber: $scope.stockNumber, toyName: $scope.name, unitPrice: $scope.price }
            $scope.toys.push(toy);
            // Reset the form section that had the new values
            $scope.stockNumber = "";
            $scope.name = "";
            $scope.price = "0.00";
        }   
    }
</script>
</body>
</html>

This would produce:

A Repeating Directive

In the same way, if you had specified the value of a property of an object as an array, in the webpage, you can access the property by preceding it with the name of the object. Here is an example:

File: Scripts/repair.js

var app = angular.module("CPARApp", []);
app.controller("CPARController", ['$scope', ['$scope', repair]]);

function repair($scope) {
    $scope.repairOrder = {
        orderNumber : 100001,
        customerName: 'Anthony Schiff',
        parts : [ { partName: "Air Filter", price: 8.95 },
                  { partName: "Gasket Intake Manifold", price: 225.67 },
                  { partName: 'Front Wheel Hub Bearing Kit', price: 96.88 },
                  { partName: "Oil Seal", price: 6.34 } ]
    };
}

File: RepairOrder.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
.bold { font-weight: 600 }
</style>
<title>College Park Auto-Repair</title>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/repair.js"></script>
</head>
<body>
<div ng-app="CPARApp" ng-controller="CPARController">
    <h1>College Park Auto-Repair</h1>
    <h2>Repair Order</h2>
    
    <table>
        <tr>
            <td class="bold">Order #:</td>
            <td>{{repairOrder.orderNumber}}</td>
        </tr>
        <tr>
            <td class="bold">Customer Name:</td>
            <td>{{repairOrder.customerName}}</td>
        </tr>
    </table>
    <hr />
    <h2 class="center">Parts Used</h2>
    <table border="4">
        <tr>
            <td class="bold">Past Name</td>
            <td class="bold">Price</td>
        </tr>
        <tr ng-repeat="part in repairOrder.parts">
            <td>{{part.partName}}</td>
            <td>{{part.price}}</td>
        </tr>
    </table>
</div>
</body>
</html>

This would produce:

An Array as a Property

Common Operations on Arrays of Objects

Removing an Element from an Array

To remove an element that exists in an array, you can call the pop()method of the Array class.

An Object is an Array

In our introduction to Arrays and objects in JavaScript, we saw that, when you create an object, each property ( defined in two parts separated by a column) becomes an element of an array and the object becomes that array. Here is an example:

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

    function present() {
        this.customers = ["Joseph", "Patricia", "Anthony", "Valerie", "Cynthia"];
        this.states = {
            8: "DC",
            6: 'MD',
            0: "PA",
            7.50: 'VA',
            7.75: "WV"
        };
    }
</script>

You can then use the properties of the object as an array. For example, you use their values to fill a combo box. Here are examples:

JavaScript File: CustomerAccount.js

function manageCustomersAccounts() {
    this.accountsTypes = {
        0: 'Residence',
        h: "Hospital",
        Gov: 'Government',
        true: 'Non-Profit Institution'
    };
    this.states = {
        AL: 'Alabama',        AK: 'Alaska',         AZ: 'Arizona',
        AR: 'Arkansas',       CA: 'California',     CO: 'Colorado',
        CT: 'Connecticut',    DE: 'Delaware',       DC: 'District of Columbia',
        FL: 'Florida',        GA: 'Georgia',        HI: 'Hawaii',
        ID: 'Idaho',          IL: 'Illinois',       IN: 'Indiana',
        IA: 'Iowa',           KS: 'Kansas',         KY: 'Kentucky',
        LA: 'Louisiana',      ME: 'Maine',          MD: 'Maryland',
        MA: 'Massachusetts',  MI: 'Michigan',       MN: 'Minnesota',
        MS: 'Mississippi',    MO: 'Missouri',       MT: 'Montana',
        NE: 'Nebraska',       NV: 'Nevada',         NH: 'New Hampshire',
        NJ: 'New Jersey',     NM: 'New Mexico',     NY: 'New York',
        NC: 'North Carolina', ND: 'North Dakota',   OH: 'Ohio',
        OK: 'Oklahoma',       OR: 'Oregon',         PA: 'Pennsylvania',
        RI: 'Rhode Island',   SC: 'South Carolina', SD: 'South Dakota',
        TN: 'Tennessee',      TX: 'Texas',          UT: 'Utah',
        VT: 'Vermont',        VA: 'Virginia',       WA: 'Washington',
        WV: 'West Virginia',  WI: 'Wisconsin',      WY: 'Wyoming'
    };
};

appCableCompany.controller("AccountController", manageCustomersAccounts);

HTML File: CustomerAccount.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ESCAPE - New Customer Account</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<link href="Content/CableCompany.css" rel="stylesheet" />
<script src="Scripts/angular.min.js"></script>
    <script src="Scripts/CableCompany.js"></script>
<script src="Scripts/CustomerAccount.js"></script>
</head>
<body ng-app="appCableCompany">
    <h1 class="text-center main-title bold">Eastern Shore Company and Production Entertainment</h1>
    <h2 class="text-center main-title bold">New Customer Account</h2>

<form name="Customer" method="post" class="formula" ng-controller="AccountController as ac">
    <table>
        <tr>
            <td><label for="AccountNumber">Account #:</label></td>
            <td><input id="AccountNumber" class="form-control" ng-model="ac.accountNumber" /></td>
        </tr>
        <tr>
            <td><label for="FirstName">First Name:</label></td>
            <td><input id="FirstName" class="form-control" ng-model="ac.firstName" /></td>
        </tr>
        <tr>
            <td><label for="LastName">Last Name:</label></td>
            <td><input id="LastName" class="form-control" ng-model="ac.lastName" /></td>
        </tr>
        <tr>
            <td><label for="AccountType">Account Type:</label></td>
            <td><select id="AccountType" class="form-control" ng-model="ac.accountType">
                    <option ng-repeat="category in ac.accountsTypes">{{category}}</option>
                </select></td>
        </tr>
        <tr>
            <td><label for="Address">Address:</label></td>
            <td><input id="Address" class="form-control large-text" ng-model="ac.address" /></td>
        </tr>
        <tr>
            <td><label for="State">State:</label></td>
            <td>
                <select id="State" class="form-control" ng-model="ac.state">
                    <option ng-repeat="stt in ac.states">{{stt}}</option>
                </select>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

Passing an Array of Objects to a Function

When adding a method to an object created in the function of a controller, you may want the method to take an array as argument. The steps and/or descriptions are the same we reviewed for JavaScript. When creating the method, simply provide a name for the parameter. Here is an example:

var app = angular.module("CPARApp", []);
app.controller("CPARController", repair);

function repair($scope) {
    $scope.repairOrder = {};
    $scope.repairOrder.orderNumber = 100001;
    $scope.repairOrder.customerName = 'Professor Kabba';
    $scope.repairCost = function(jobsPrices)...
}

In the same way, a method can use more than one parameter, and one or more of those parameters can represent (an) array(s). Here is an example:

var app = angular.module("CPARApp", []);
app.controller("CPARController", ['$scope', repair]);

function repair($scope) {
    $scope.repairOrder = {};
    $scope.repairOrder.orderNumber = 100001;
    $scope.repairOrder.customerName = 'Professor Kabba';
    $scope.repairOrder.repairCost = function(completed, jobsPrices)...
}

Once again, at this time, the method does't know what type(s) of parameter(s) it is dealing with. In the body of the method, it is up to you to treat a parameter as array. Here is an example:

var app = angular.module("CPARApp", []);
app.controller("CPARController", ['$scope', repair]);

function repair($scope) {
    $scope.repairOrder = {};
    $scope.repairOrder.orderNumber = 100001;
    $scope.repairOrder.customerName = 'Professor Kabba';
    $scope.repairOrder.repairCost = function(completed, jobsPrices){
        if (completed == true) {
            var cost = 0.00;

            for (var price in jobsPrices) {
                cost += jobsPrices[price];
            }

            return cost;
        }
        else {
            return 0.00;
        }   
    }
    
}

When calling the method, if you don't (yet) have the elements of the array/argument, you can pass the argument with empty square brackets. Here are examples:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
.bold { font-weight: 600 }
</style>
<title>College Park Auto-Repair</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="CPARApp">
    <div ng-controller="CPARController">
        <h1>College Park Auto-Repair</h1>
        <h2>Repair Order</h2>

        <table>
            <tr>
                <td class="bold">Order #:</td>
                <td>{{repairOrder.orderNumber}}</td>
            </tr>
            <tr>
                <td class="bold">Customer Name:</td>
                <td>{{repairOrder.customerName}}</td>
            </tr>
            <tr>
                <td class="bold">Amount Owed:</td>
                <td>{{repairOrder.repairCost(true, [])}}</td>
            </tr>
        </table>
    </div>
<script type="text/javascript">
    var app = angular.module("CPARApp", []);
    app.controller("CPARController", ['$scope', function repair($scope) {
        $scope.repairOrder = {};
        $scope.repairOrder.orderNumber = 100001;
        $scope.repairOrder.customerName = 'Professor Kabba';
        $scope.repairOrder.repairCost = function (completed, jobsPrices) {
            if (completed == true) {
                var cost = 0.00;

                for (var price in jobsPrices) {
                    cost += jobsPrices[price];
                }

                return cost;
            }
            else {
                return 0.00;
            }
        }
    }]);
</script>
</body>
</html>

This would produce:

Passing an Array to a Function

Otherwise, if you have the elements of the array, you can pass their array as argument. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
.bold { font-weight: 600 }
</style>
<title>College Park Auto-Repair</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="CPARApp">
    <div ng-controller="CPARController">
        <h1>College Park Auto-Repair</h1>
        <h2>Repair Order</h2>

        <table>
            <tr>
                <td class="bold">Order #:</td>
                <td>{{repairOrder.orderNumber}}</td>
            </tr>
            <tr>
                <td class="bold">Customer Name:</td>
                <td>{{repairOrder.customerName}}</td>
            </tr>
            <tr>
                <td class="bold">Amount Owed:</td>
                <td>{{repairOrder.repairCost(true, [24.95, 68.82, 17.74, 32.68])}}</td>
            </tr>
        </table>
    </div>
<script type="text/javascript">
    var app = angular.module("CPARApp", []);
    app.controller("CPARController", ['$scope', function ($scope) {
        $scope.repairOrder = {};
        $scope.repairOrder.orderNumber = 100002;
        $scope.repairOrder.customerName = 'Raymond Martyns';
        $scope.repairOrder.repairCost = function (completed, jobsPrices) {
            if (completed == true) {
                var cost = 0.00;

                for (var price in jobsPrices) {
                    cost += jobsPrices[price];
                }

                return cost;
            }
            else {
                return 0.00;
            }
        }
    }]);
</script>
</body>
</html>

This would produce:

Access to Members of a Jagged Array

Of course, you can use the same concept if the elements of the array/arguments are objects.


Previous Copyright © 2018-2019, FunctionX Next