Arrays of Objects and Services
Arrays of Objects and Services
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 Learning: Introducing Arrays in Services
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; }
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]);
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 Learning: Accessing the Objects
<!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>
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 Learning: Looping an Array of Objects
<!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>
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> </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:
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:
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:
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 Learning: Ending the Lesson
|
||
Previous | Copyright © 2018-2022, FunctionX | Next |
|