AngularJS Factory Services
AngularJS Factory Services
A Factory Service
Introduction
So far, we created our services as regular functions that carry an assignment. AngularJS provides an option to create a service as a formal object. That object would include one or more properties and/or one or more methods that can be used to perform various types of operations.
Practical Learning: Introducing Factory Services
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; } .top-padding { padding-top: 0.50em; } .common-font { font-family: Georgia, 'Times New Roman', Times, serif; }
var appUtilityCompany = angular.module("appUtilities", []); appUtilityCompany.controller("UtilitiesController", prepare); function prepare() { }
using System.Web.Optimization; namespace GasUtilityCompany1 { 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")); 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/Utilities.css")); } } }
using System.Web.Mvc;
namespace GasUtilityCompany1.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();
}
}
}
@{ ViewBag.Title = "Bill Evaluation"; } @Scripts.Render("~/bundles/jquery") <div ng-app="appUtilities"> <div class="bill-contents"> <h2 class="font bold text-center">Bill Preparation</h2> </div> <hr /> <div class="bill-contents" ng-controller="UtilitiesController"></div> </div>
<!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">© @DateTime.Now.Year - Gas Utility Company</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
Creating a Factory Service
To let you create a service that is carried by an object, the angular object is equipped with a method named factory. Its syntax is:
factory(string name, function function-definition);
As seen for a controller or a service service, to create a factory service, you must add or attach it to an existing module and create it as a member of that module.
The first argument of the angular.factory() method is the intended name of the service. The second argument represents a function. As done previously, you can define a function separately and pass its name as the second argument. Here is an example:
var app = angular.module("appExercise", []);
app.factory('titleFactory', inspire);
function inspire() {
}
As mentioned for a controller or a service service, you can create a factory service in the same file that contains the module or you can create it in its own document. If you decide to do that, create a document and save its file with the .js extension. In the HTML document where you want to use the service, create a link to that file.
Practical Learning: Creating a Factory Service
appUtilityCompany.factory("billsManagement", Manage); function Manage() { }
using System.Web.Optimization;
namespace GasUtilityCompany1
{
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/BillsManagement.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/Utilities.css"));
}
}
}
Using a Factory Service
After creating a factory service, to use it, pass its name as argument to the function of the controller. You can create the service in the same document that contains the controller. Here is an example:
var app = angular.module("appExercise", []); app.factory('titleFactory', inspire); app.controller("RevelationController", enjoy); function inspire() { } function enjoy(titleFactory) { }
Practical Learning: Using a Factory Service
var appUtilityCompany = angular.module("appUtilities", []);
appUtilityCompany.controller("UtilitiesController", prepare);
function prepare(billsManagement) {
}
Introduction to the Factory Service as an Object
A Service as a Constant Value
As seen with a service created using the angular.service() method, when creating a service using the angular.factory() method, the function of a factory must return something. As one option, in the body of the factory function, you can define a constant or a value and return it. Here is an example:
function inspire() {
return "The Seven Wonders of the World";
}
To access the value returned by the factory-based function, in the function of the controller, simply use the name of the service. Here is an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="appExercise">
<script type="text/javascript">
var app = angular.module("appExercise", []);
app.factory('titleFactory', inspire);
app.controller("RevelationController", enjoy);
function inspire() {
return "The Seven Wonders of the World";
}
function enjoy(titleFactory) {
this.illustration = titleFactory;
}
</script>
<p ng-controller="RevelationController as rc">{{rc.illustration}}</p>
</body>
</html>
Practical Learning: Using a Service as a Constant Value
appUtilityCompany.factory("Management", manage);
function manage() {
return "Welcome to our client-oriented, customer friendly, and web-based application. This app will assist you in evaluating your monthly gas bill.";
}
var appUtilityCompany = angular.module("appUtilities", []);
appUtilityCompany.controller("UtilitiesController", prepare);
function prepare(billsManagement) {
this.introduction = billsManagement;
}
@{ ViewBag.Title = "Bill Evaluation"; } @Scripts.Render("~/bundles/jquery") <div ng-app="appUtilities"> <div class="bill-contents"> <h2 class="font bold text-center">Bill Preparation</h2> </div> <hr /> <div class="bill-contents" ng-controller="UtilitiesController as uc"> <p>{{uc.introduction}}</p> </div> </div>
A Factory Service as an Object
One of the characteristics of a factory is that it is meant to produce an object. To make this happen, create a JavaScript object in the function of the factory. The function of the factory must return that object.
Practical Learning: Creating an Object for a Service
appUtilityCompany.factory("Management", manage);
function manage() {
var gasBill = {
};
return gasBill;
}
A Property of a Service
In the body of the object, you can add the necessary memberss, such as properties. Here is an example of an object that contains a property:
function inspire() {
var inspiration = {
introducetion : "Sociology is the study of the various aspects of the society in general. Sociology can also be confined to a specific aspect.";
};
return inspiration;
}
To accesss a property of a factory object, in the function of the controller, type the name of the service, a period, and the name of the property. Here is an example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="appExercise">
<script type="text/javascript">
var app = angular.module("appExercise", []);
app.factory('socioFactory', inspire);
app.controller("RevelationController", enjoy);
function inspire() {
var inspiration = {
introduction : "Sociology is the study of the various aspects of the society in general. Sociology can also be confined to a specific aspect.";
}
};
return inspiration;
}
function enjoy(socioFactory) {
this.definition = socioFactory.introduction;
}
</script>
<div ng-controller="RevelationController as rc">
<p><b>Introduction:</b> {{rc.definition}}</p>
</div>
</body>
</html>
In the same way, you can add as many properties as you want to a factory object.
Practical Learning: Adding Properties to a Factory
appUtilityCompany.factory("billsManagement", manage);
function manage() {
var gasBill = {
beginReading: 214485,
endReading: 216079
};
return gasBill;
}
var appUtilityCompany = angular.module("appUtilities", []);
appUtilityCompany.controller("UtilitiesController", prepare);
function prepare(billsManagement) {
this.counterReadingStart = billsManagement.beginReading;
this.counterReadingEnd = billsManagement.endReading;
}
@{
ViewBag.Title = "Bill Evaluation";
}
@Scripts.Render("~/bundles/jquery")
<div ng-app="appUtilities">
<div class="bill-contents">
<h2 class="font bold text-center common-font">Bill Evaluation</h2>
</div>
<hr />
<div class="bill-contents" ng-controller="UtilitiesController as uc">
<form method="post" name="BillPreparation" class="common-font">
<table class="table table-condensed">
<tr>
<td class="left-column"><label for="CounterReadingStart" class="top-padding">Counter Reading Start:</label></td>
<td><input type="text" id="CounterReadingStart" ng-model="uc.counterReadingStart" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label for="CounterReadingEnd" class="top-padding">Counter Reading End:</label></td>
<td><input type="text" id="CounterReadingEnd" ng-model="uc.counterReadingEnd" class="form-control txtContext" /></td>
</tr>
</table>
</form>
</div>
</div>
Performing Operations on a Service
Introduction to the Methods of a Service
Besised properties, you can create one or more methods in the object of a service. In fact, if you want a service to perform some operations, add the desired methods to it. To add a method, create an anonymous function and assign it to a name in the object. In the same way, you can add as many methods as you want. Here are examples:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Exercise</title> <script src="Scripts/angular.min.js"></script> </head> <body ng-app="appExercise"> <script type="text/javascript"> var app = angular.module("appExercise", []); app.factory('socioFactory', inspire); app.controller("RevelationController", enjoy); function inspire() { var inspiration = { introduce: function () { return "Sociology is the study of the various aspects of the society in general. Sociology can also be confined to a specific aspect."; }, culture : function () { return "Culture is a branch of sociology that that studies human behavior and all of the aspects that influence it."; }, welfare: function () { return "Welfare consists of the norms that contribute to the general well-being of members of a particular social group."; } }; return inspiration; } function enjoy(socioFactory) { this.definition = socioFactory.introduce(); this.aspect = socioFactory.culture(); this.living = socioFactory.welfare(); } </script> <div ng-controller="RevelationController as rc"> <p><b>Introduction:</b> {{rc.definition}}</p> <p><b>Culture:</b> {{rc.aspect}}</p> <p><b>Welfare and Well-Being: </b>{{rc.living}}</p> </div> </body> </html>
In a controller, you can access a method the same way you access a property, except that, for a method, you must add parentheses.
Practical Learning: Adding Methods to a Service
appUtilityCompany.factory("billsManagement", manage); function manage() { var gasBill = { beginReading: 214485, endReading: 216079, readingDifference: function () { return gasBill.endReading - gasBill.beginReading; }, therms: function () { return gasBill.readingDifference() * 1.0367; }, adjust: function () { return gasBill.therms() * 0.13086; }, carrying : function () { var thrm = gasBill.therms(); if (thrm <= 5000) return thrm * 0.016289; else return thrm * 0.009577; }, deliv : function () { var thrm = gasBill.therms(); var trans = gasBill.carrying(); var first50Therms = 0, over50Therms = 0; if (thrm < 5000) { first50Therms = thrm * 0.05269; over50Therms = 0; } else { first50Therms = 5000 * 0.5269; over50Therms = (thrm - 5000) * 0.04995; } return trans + gasBill.adjust() + first50Therms + over50Therms; }, enviro: function () { return gasBill.deliv() * 0.0045; }, pmt: function () { return gasBill.deliv() + gasBill.enviro(); } }; return gasBill; }
var appUtilityCompany = angular.module("appUtilities", []); appUtilityCompany.controller("UtilitiesController", prepare); function prepare(billsManagement) { this.counterReadingStart = billsManagement.beginReading; this.counterReadingEnd = billsManagement.endReading; this.CCFTotal = billsManagement.readingDifference(); this.totalTherms = billsManagement.therms(); this.ditributionAdjustment = billsManagementManagement.adjust(); this.transportationCharges = billsManagementManagement.carrying(); this.totalDelivery = billsManagementManagement.deliv(); this.environmentCharges = billsManagementManagement.enviro(); this.amountDue = billsManagementManagement.pmt(); }
@{
ViewBag.Title = "Bill Evaluation";
}
@Scripts.Render("~/bundles/jquery")
<div ng-app="appUtilities">
<div class="bill-contents">
<h2 class="font bold text-center common-font">Bill Evaluation</h2>
</div>
<hr />
<div class="bill-contents" ng-controller="UtilitiesController as uc">
<form method="post" name="BillPreparation" class="common-font">
<table class="table table-condensed">
<tr>
<td class="left-column"><label for="CounterReadingStart" class="top-padding">Counter Reading Start:</label></td>
<td><input type="text" id="CounterReadingStart" ng-model="uc.counterReadingStart" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label for="CounterReadingEnd" class="top-padding">Counter Reading End:</label></td>
<td><input type="text" id="CounterReadingEnd" ng-model="uc.counterReadingEnd" class="form-control txtContext" /></td>
</tr>
</table>
<hr />
<table class="table table-condensed">
<tr>
<td class="left-column"><label class="bold top-padding">CCF Total:</label></td>
<td><input type="text" ng-model="uc.CCFTotal" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Total Therms:</label></td>
<td><input type="text" ng-model="uc.totalTherms | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Ditribution Adjustment:</label></td>
<td><input type="text" ng-model="uc.ditributionAdjustment | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Transportation Charges:</label></td>
<td><input type="text" ng-model="uc.transportationCharges | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Total Delivery:</label></td>
<td><input type="text" ng-model="uc.totalDelivery | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Environment Charges:</label></td>
<td><input type="text" ng-model="uc.environmentCharges | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Amount Due:</label></td>
<td><input type="text" ng-model="uc.amountDue | number: 2" class="form-control txtContext" /></td>
</tr>
</table>
</form>
</div>
</div>
Passing Values to a Service
You can provide one or more external values to a factory service. To do this, when creating a method in the factory objeect, provide one or more parameters to the parentheses of the method. When calling the method, make sure you pass the appropriate argument(s).
Practical Learning: Passing Values to a Service
appUtilityCompany.factory("billsManagement", manage);
function manage() {
var gasBill = {
readingDifference: function (beginning, ending) {
return ending - beginning;
},
therms: function (beginning, ending) {
return (ending - beginning) * 1.0367;
},
adjust: function (beginning, ending) {
return ((ending - beginning) * 1.0367) * 0.13086;
},
carrying: function (beginning, ending) {
var thrm = gasBill.therms(beginning, ending);
if (thrm <= 5000)
return thrm * 0.016289;
else
return thrm * 0.009577;
},
deliv: function (beginning, ending) {
var thrm = gasBill.therms(beginning, ending);
var trans = gasBill.carrying(beginning, ending);
var first50Therms = 0, over50Therms = 0;
if (thrm < 5000) {
first50Therms = thrm * 0.05269;
over50Therms = 0;
}
else {
first50Therms = 5000 * 0.5269;
over50Therms = (thrm - 5000) * 0.04995;
}
return trans + gasBill.carrying(beginning, ending) + first50Therms + over50Therms;
},
enviro: function (beginning, ending) {
return gasBill.deliv(beginning, ending) * 0.0045;
},
pmt: function (beginning, ending) {
return gasBill.deliv(beginning, ending) + gasBill.enviro(beginning, ending);
}
};
return gasBill;
}
var appUtilityCompany = angular.module("appUtilities", []); appUtilityCompany.controller("UtilitiesController", prepare); function prepare(billsManagement) { this.evaluate = function () { var start = Number(this.counterReadingStart || 0); var finish = Number(this.counterReadingEnd || 0); this.CCFTotal = billsManagement.readingDifference(start, finish); this.totalTherms = billsManagement.therms(start, finish); this.ditributionAdjustment = billsManagement.adjust(start, finish); this.transportationCharges = billsManagement.carrying(start, finish); this.totalDelivery = billsManagement.deliv(start, finish); this.environmentCharges = billsManagement.enviro(start, finish); this.amountDue = billsManagement.pmt(start, finish); } }
@{
ViewBag.Title = "Bill Evaluation";
}
@Scripts.Render("~/bundles/jquery")
<div ng-app="appUtilities">
<div class="bill-contents">
<h2 class="font bold text-center common-font">Bill Evaluation</h2>
</div>
<hr />
<div class="bill-contents" ng-controller="UtilitiesController as uc">
<form method="post" name="BillPreparation" class="common-font">
<table class="table table-condensed">
<tr>
<td><label for="CounterReadingEnd" class="top-padding">Counter Reading End:</label></td>
<td><input type="text" id="CounterReadingEnd" ng-model="uc.counterReadingEnd"
class="form-control txtContext" ng-change="uc.evaluate()" /></td>
</tr>
<tr>
<td class="left-column"><label for="CounterReadingStart" class="top-padding">Counter Reading Start:</label></td>
<td><input type="text" id="CounterReadingStart" ng-model="uc.counterReadingStart"
class="form-control txtContext" ng-change="uc.evaluate()" /></td>
</tr>
</table>
<hr />
<table class="table table-condensed">
<tr>
<td class="left-column"><label class="bold top-padding">CCF Total:</label></td>
<td><input type="text" ng-model="uc.CCFTotal" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Total Therms:</label></td>
<td><input type="text" ng-model="uc.totalTherms | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Ditribution Adjustment:</label></td>
<td><input type="text" ng-model="uc.ditributionAdjustment | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Transportation Charges:</label></td>
<td><input type="text" ng-model="uc.transportationCharges | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Total Delivery:</label></td>
<td><input type="text" ng-model="uc.totalDelivery | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Environment Charges:</label></td>
<td><input type="text" ng-model="uc.environmentCharges | number: 2" class="form-control txtContext" /></td>
</tr>
<tr>
<td><label class="top-padding">Amount Due:</label></td>
<td><input type="text" ng-model="uc.amountDue | number: 2" class="form-control txtContext" /></td>
</tr>
</table>
</form>
</div>
</div>
|
||
Previous | Copyright © 2017-2022, FunctionX | Next |
|