Arrays in Services

Introduction

AngularJS Services support arrays of objects the same way a controller does. As seen previously, you can create the array in the constructor of the service. You can first create an object and add it to an array. Here is an exmple:

var appModule = angular.module("clienteleModule", []);
appModule.controller("ClienteleController", present);

function present($scope) {
   var eneh = {
        accountNumber: "85-2853-74",
        firstName: "Elijah",
        lastName: "Neheman",
        address: "6804 West Cliff Rd",
        city: "Rockville",
        county: "Montgomery",
        state: "MD" };

    $scope.customers = [ eneh ];
}

You can also first create objects and add each to an array. Here is an example:

var appModule = angular.module("clienteleModule", []);
appModule.controller("ClienteleController", ['$scope', present]);

function present($scope) {
   var eneh = {
        accountNumber: "85-2853-74",
        firstName: "Elijah",
        lastName: "Neheman",
        address: "6804 West Cliff Rd",
        city: "Rockville",
        county: "Montgomery",
        state: "MD" };

    var pebou = {
        accountNumber : "62-3850-80",
        firstName : "Patricia",
        lastName : "Eboutou",
        address : "10422 South Sailer Court",
        city : "College Park",
        county : "Prince Georges",
        state : "MD" };
            
$scope.customers = [ eneh, pebou ];

You can also create the objects directly in the square brackets of the array as we saw in JavaScript.

Practical LearningPractical Learning: Introducing Arrays in Services

  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 CableCompany6
  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 CableCompany6 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 CableCompany
  12. Click Add
  13. Change the document as follows:
    body {
        background-color: white;
    }
    
    .bold              { font-weight: 600;   }
    .main-title        { color:       maroon;
                         font-family: 'Times New Roman', Garamond, Georgia, serif; }
    .centered-contents { margin:      auto; 
                         width:       750px; }
  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 CustomersService
  17. Click Add
  18. In the empty document, type the following code:
    function createCustomersAccounts() {
        this.customers = [
            {
                accountNumber: "85-2853-74",
                firstName: "Elijah", lastName: "Neheman",
                address: "6804 West Cliff Rd",
                city: "Rockville", county: "Montgomery", state: "MD"
            },
            {
                accountNumber: "62-3850-80",
                firstName: "Patricia", lastName: "Eboutou",
                address: "10422 South Sailer Court",
                city: "College Park", county: "Prince Georges", state: "MD"
            },
            {
                accountNumber: "15-8364-96",
                firstName: "Martha", lastName: "Thiel",
                address: "7284 Woorhies Ave", city: "Alexandria", state: "VA"
            },
            {
                accountNumber: "72-8304-75",
                firstName: "Patricia", lastName: "Healey",
                address: "3997 Ghost Effect Str",
                city: "Hedgesville", county: "Berkeley", state: "WV"
            }];
    };
    
    appCableCompany.service("customersRecords", [createCustomersAccounts]);
  19. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  20. Change the Name of the file to CableCompany
  21. Click Add
  22. In the empty document, type the following:
    var appCableCompany = angular.module('appCableCompany', []);
    
    function manageCustomersAccounts(customersRecords) {
        this.accounts = customersRecords.customers;
    };
    
    appCableCompany.controller("BusinessController", ['customersRecords', manageCustomersAccounts]);

Accessing the Objects of a Service-Based Array

You can access each object of the array using the square brackets applied to the name of the object.

Practical LearningPractical Learning: Accessing the Objects

  1. In the Solution Explorer, right-click CableCompany6 -> Add -> HTML Page
  2. Type CustomerAccount as the name of the file
  3. Click OK
  4. Change the document as follows:
    <!DOCTYPE html>
    <html ng-app="appCableCompany">
    <head>
    <meta charset="utf-8" />
    <title>ESCAPE - Customer Account</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/CableCompany.js"></script>
    <script src="Scripts/CustomersService.js"></script>
    </head>
    <body ng-controller="BusinessController as client">
    <h1>ESCAPE - Customer Record</h1>
    
    <table ng-controller="BusinessController as client">
        <tr>
            <td style="font-weight: 600; width: 100px">Account #:</td>
            <td>{{client.accounts[1].accountNumber}}</td>
        </tr>
        <tr>
            <td style="font-weight: 600">First Name:</td>
            <td>{{client.accounts[1].firstName}}</td>
        </tr>
        <tr>
            <td style="font-weight: 600">Last Name:</td>
            <td>{{client.accounts[1].lastName}}</td>
        </tr>
        <tr>
            <td style="font-weight: 600">Address:</td>
            <td>{{client.accounts[1].address}}</td>
        </tr>
        <tr>
            <td style="font-weight: 600">City:</td>
            <td>{{client.accounts[1].city}}</td>
        </tr>
        <tr>
            <td style="font-weight: 600">County:</td>
            <td>{{client.accounts[1].county}}</td>
        </tr>
        <tr>
            <td style="font-weight: 600">State:</td>
            <td>{{client.accounts[1].state}}</td>
        </tr>
    </table>
    </body>
    </html>
  5. To execute the project, press Ctrl + F5
  6. Accessing the Elements of the Array

  7. Close the browser and return to your programming environment

Repeating Access to an Array of Objects

If you want to repeatedly access each object of a service-based array, you can use the ng-repeat directive. To do this, get the list in the controller and treat as if it were a local array.

Practical LearningPractical Learning: Looping an Array of Objects

  1. In the Solution Explorer, right-click CableCompany6 -> Add -> HTML Page
  2. Type CustomersRecords as the name of the file
  3. Click OK
  4. Change the document as follows:
    <!DOCTYPE html>
    <html ng-app="appCableCompany">
    <head>
    <meta charset="utf-8" />
    <title>ESCAPE - Customers Records</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/CableCompany.js"></script>
    <script src="Scripts/CustomersService.js"></script>
    </head>
    <body ng-controller="BusinessController as client">
    <h1>ESCAPE - Customers Records</h1>
        
    <table border="4">
        <tr>
            <td style="font-weight: 600; width: 100px">Account #</td>
            <td style="font-weight: 600">First Name</td>
            <td style="font-weight: 600">Last Name</td>
            <td style="font-weight: 600">Address</td>
            <td style="font-weight: 600">City</td>
            <td style="font-weight: 600">County</td>
            <td style="font-weight: 600">State</td>
        </tr>
        <tr ng-repeat="customer in client.accounts">
            <td>{{customer.accountNumber}}</td>
            <td>{{customer.firstName}}</td>
            <td>{{customer.lastName}}</td>
            <td>{{customer.address}}</td>
            <td>{{customer.city}}</td>
            <td>{{customer.county}}</td>
            <td>{{customer.state}}</td>
        </tr>
    </table>
    </body>
    </html>
  5. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    A Repeating Directive

  6. Close the browser and return to your programming environment

Routine Operations on Arrays of Objects

Adding an Element to an Array

As seen earlier for regular elements, to add an object to an array, you can call the push() that the arrays inherit from their parenth class. Here are two examples of calling the method:

<!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', ['$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

Removing an Element from an Array

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

Passing an Array 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", ['$scope', 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', 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', function ($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 ($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", repair);

    function repair($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

Factory Services and Arrays of Objects

Factory services support arrays the way arrays are created in an object. This means that, in the constructor of a service, you can create an array and assign it to a this-based property.

Practical LearningPractical Learning: Ending the Lesson

  1. Close your programming environment

Previous Copyright © 2018-2019, FunctionX Next