The Methods of a Service

Introduction

A property is usually suited for a constant value you want to access in the controller. If you want a functionality that processes and/or validates some values, you should add a method to the service.

Practical LearningPractical Learning: Introducing AngularJS 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 PayrollPreparation2
  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 PayrollPreparation2 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;
    }
    
    .bold        { font-weight: 600;   }
    .ng-model    { width:       100px; }
    .large-text  { width:       120px; }
    .left-column { width:       150px; }
    .delimiter   { margin:      auto;
                   width:       700px; }
    .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; }

Creating a Method

We already know that JavaScript supports nested functions. If you want to add a method to a service, nest a function in its constructor. To do this, attach a name to the this object and assign a method definition to it. If the method must produce a value that will be accessed in the controller, make sure it returns a value. Here is an example:

function announce() {
    this.validateUsername = function () {
        return "The username you are trying to create is not valid (too short or too long). Make sure your new username has 6 to 8 characters";
    }
}

In the same way, you can create as many methods as you want in the constructor of a service. To call a method of a service in the controller, apply the name of the service to it and make sure you use the parentheses. 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="appTimeSheet">
<script>
    var app = angular.module('appTimeSheet', []);
    app.service('tsService', announce);
    app.controller("TimeSheetController", present);

    function announce() {
        this.validateUsername = function () {
            return "The username you are trying to create is not valid (too short or too long). Make sure your new username has 6 to 8 characters";
        }
        
        this.checkPassword = function () {
            return "The password you have provided doesn't meet our criteria. Make sure you provide at least 2 lowercase letters, 2 uppercase letters, 2 digits, and 2 special characters.";
        }
    }

    function present(tsService) {
        this.user = tsService.validateUsername();
        this.pass = tsService.checkPassword();
    }
</script>
<div ng-controller="TimeSheetController as tsc">
    <p><b>Error:</b> {{tsc.user}}</p>
    <p><b>Warning:</b> {{tsc.pass}}</p>
</div>
</body>
</html>

Of course, you can define the whole constructor in its placeholder of the service. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Kolo Bank</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="appTimeSheet">
<script>
    var app = angular.module('appTimeSheet', []);
    app.service('tsService', function () {
        this.validateUsername = function () {
            return "The username you are trying to create is not valid (too short or too long). Make sure your new username has 6 to 8 characters";
        }

        this.checkPassword = function () {
            return "The password you have provided doesn't meet our criteria. Make sure you provide at least 2 lowercase letters, 2 uppercase letters, 2 digits, and 2 special characters.";
        }
    });
    app.controller("TimeSheetController", present);

    function present(tsService) {
        this.user = tsService.validateUsername();
        this.pass = tsService.checkPassword();
    }
</script>

<div ng-controller="TimeSheetController as tsc">
    <p><b>Error:</b> {{tsc.user}}</p>
    <p><b>Warning:</b> {{tsc.pass}}</p>
</div>
</body>
</html>

Practical LearningPractical Learning: Adding Functions to a Service

  1. In the Solution Explorer, right-click Scripts -> Add -> New Item...
  2. In the left frame of the Add New Item dialog box, click Web and, in the middle frame, click JavaScript File
  3. Change the Name of the file to TimeSheetEvaluation
  4. Click Add
  5. In the empty document, type the following code:
    function calculateSalary() {
        function calculateRegularTime(time) {
            if (time <= 8.00)
                return time;
            else
                return 8.00;
        }
        function calculateOvertime(time) {
            if (time <= 8.00)
                return 0.00;
            else
                return time - 8.00;
        }
    
        var hSal = 16.29;
        var overtimeRate = hSal * 1.50;
        var mon = 10.50, tue = 9.00, wed = 7.50, thu = 9.50, fri = 6.00;
    
        var monRegTime = calculateRegularTime(mon);
        var tueRegTime = calculateRegularTime(tue);
        var wedRegTime = calculateRegularTime(wed);
        var thuRegTime = calculateRegularTime(thu);
        var friRegTime = calculateRegularTime(fri);
    
        var monRegSal = hSal * monRegTime;
        var tueRegSal = hSal * tueRegTime;
        var wedRegSal = hSal * wedRegTime;
        var thuRegSal = hSal * thuRegTime;
        var friRegSal = hSal * friRegTime;
    
        var monOver = calculateOvertime(mon);
        var tueOver = calculateOvertime(tue);
        var wedOver = calculateOvertime(wed);
        var thuOver = calculateOvertime(thu);
        var friOver = calculateOvertime(fri);
    
        var monOverPay = overtimeRate * monOver;
        var tueOverPay = overtimeRate * tueOver;
        var wedOverPay = overtimeRate * wedOver;
        var thuOverPay = overtimeRate * thuOver;
        var friOverPay = overtimeRate * friOver;
    
        this.baseRate = hSal;
        this.monWork = mon;
        this.tueWork = tue;
        this.wedWork = wed;
        this.thuWork = thu;
        this.friWork = fri;
    
        this.monRegularTime = function () { return monRegTime; }
        this.tueRegularTime = function () { return tueRegTime; }
        this.wedRegularTime = function () { return wedRegTime; }
        this.thuRegularTime = function () { return thuRegTime; }
        this.friRegularTime = function () { return friRegTime; }
    
        this.monRegularPay = function () { return monRegSal; }
        this.tueRegularPay = function () { return tueRegSal; }
        this.wedRegularPay = function () { return wedRegSal; }
        this.thuRegularPay = function () { return thuRegSal; }
        this.friRegularPay = function () { return friRegSal; }
    
        this.monOvertime = function () { return monOver; }
        this.tueOvertime = function () { return tueOver; }
        this.wedOvertime = function () { return wedOver; }
        this.thuOvertime = function () { return thuOver; }
        this.friOvertime = function () { return friOver; }
    
        this.monOverPay = function () { return monOverPay; }
        this.tueOverPay = function () { return tueOverPay; }
        this.wedOverPay = function () { return wedOverPay; }
        this.thuOverPay = function () { return thuOverPay; }
        this.friOverPay = function () { return friOverPay; }
    
        this.weeklySalary = monRegSal + tueRegSal + wedRegSal + thuRegSal + friRegSal + monOverPay + tueOverPay + wedOverPay + thuOverPay + friOverPay;
    }
    
    appPayrollApplication.service("timeSheetService", calculateSalary);
  6. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  7. Type PayrollManagement as the name of the file
  8. Click OK
  9. Type the following code:
    var appPayrollApplication = angular.module("appPayroll", []);
    
    function processPayroll(timeSheetService) {
        this.prepare = function () {
            this.HourlySalary = timeSheetService.baseRate;
    
            this.Monday = timeSheetService.monWork;
            this.Tuesday = timeSheetService.tueWork;
            this.Wednesday = timeSheetService.wedWork;
            this.Thursday = timeSheetService.thuWork;
            this.Friday = timeSheetService.friWork;
    
            this.MondayRegularTime = timeSheetService.monRegularTime();
            this.TuesdayRegularTime = timeSheetService.tueRegularTime();
            this.WednesdayRegularTime = timeSheetService.wedRegularTime();
            this.ThursdayRegularTime = timeSheetService.thuRegularTime();
            this.FridayRegularTime = timeSheetService.friRegularTime();
    
            this.MondayRegularSalary = timeSheetService.monRegularPay();
            this.TuesdayRegularSalary = timeSheetService.tueRegularPay();
            this.WednesdayRegularSalary = timeSheetService.wedRegularPay();
            this.ThursdayRegularSalary = timeSheetService.thuRegularPay();
            this.FridayRegularSalary = timeSheetService.friRegularPay();
    
            this.MondayOvertime = timeSheetService.monOvertime();
            this.TuesdayOvertime = timeSheetService.tueOvertime();
            this.WednesdayOvertime = timeSheetService.wedOvertime();
            this.ThursdayOvertime = timeSheetService.thuOvertime();
            this.FridayOvertime = timeSheetService.friOvertime();
    
            this.MondayOvertimeSalary = timeSheetService.monOverPay();
            this.TuesdayOvertimeSalary = timeSheetService.tueOverPay();
            this.WednesdayOvertimeSalary = timeSheetService.wedOverPay();
            this.ThursdayOvertimeSalary = timeSheetService.thuOverPay();
            this.FridayOvertimeSalary = timeSheetService.friOverPay();
    
            this.NetPay = timeSheetService.weeklySalary;
        }
    
        this.prepare();
    }
    
    appPayrollApplication.controller("PayrollController", processPayroll);
  10. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  11. Change the document as follows:
    using System.Web.Optimization;
    
    namespace PayrollPreparation2
    {
        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/PayrollManagement.js",
                            "~/Scripts/TimeSheetEvaluation.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"));
            }
        }
    }
  12. In the Solution Explorer, expand Controllers and double-click HomeController.cs
  13. In the class, create a method named TimeSheetEvaluation as follows:
    using System.Web.Mvc;
    
    namespace PayrollPreparation2.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 TimeSheetEvaluation()
            {
                return View();
            }
        }
    }
  14. In the class, right-click TimeSheetEvaluation() and click Add View...
  15. In the Add View dialog box, make sure the View Name text box displays TimeSheetEvaluation. Click Add
  16. Change the document as follows:
    @{
        ViewBag.Title = "Payroll Evaluation";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <div ng-app="appPayroll">
        <h2 class="common-font text-center bold">Payroll Evaluation</h2>
        <hr />
    
        <div class="delimiter" ng-controller="PayrollController as pay">
            <form name="TimeSheetEvaluation" method="post">
                <table>
                    <tr>
                        <td class="large-text bold">Hourly Salary:</td>
                        <td colspan="5"><input type="text" class="form-control ng-model" ng-model="pay.HourlySalary" /></td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                    </tr>
                </table>
    
                <table class="table table-striped">
                    <tr>
                        <td>&nbsp;</td>
                        <td class="bold text-center">Monday</td>
                        <td class="bold text-center">Tuesday</td>
                        <td class="bold text-center">Wednesday</td>
                        <td class="bold text-center">Thursday</td>
                        <td class="bold text-center">Friday</td>
                    </tr>
                    <tr>
                        <td class="bold">Time Worked:</td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Monday" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Tuesday" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Wednesday" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Thursday" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Friday" /></td>
                    </tr>
                    <tr>
                        <td class="bold">Regular Time:</td>
                        <td>{{pay.MondayRegularTime | number: 2}}</td>
                        <td>{{pay.TuesdayRegularTime | number: 2}}</td>
                        <td>{{pay.WednesdayRegularTime | number: 2}}</td>
                        <td>{{pay.ThursdayRegularTime | number: 2}}</td>
                        <td>{{pay.FridayRegularTime | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Regular Salary:</td>
                        <td>{{pay.MondayRegularSalary | number: 2}}</td>
                        <td>{{pay.TuesdayRegularSalary | number: 2}}</td>
                        <td>{{pay.WednesdayRegularSalary | number: 2}}</td>
                        <td>{{pay.ThursdayRegularSalary | number: 2}}</td>
                        <td>{{pay.FridayRegularSalary | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Overtime:</td>
                        <td>{{pay.MondayOvertime | number: 2}}</td>
                        <td>{{pay.TuesdayOvertime | number: 2}}</td>
                        <td>{{pay.WednesdayOvertime | number: 2}}</td>
                        <td>{{pay.ThursdayOvertime | number: 2}}</td>
                        <td>{{pay.FridayOvertime | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Overtime Salary:</td>
                        <td>{{pay.MondayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.TuesdayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.WednesdayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.ThursdayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.FridayOvertimeSalary | number: 2}}</td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td class="bold">Weekly Salary:</td>
                        <td>{{pay.NetPay | number: 2}}</td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
  17. In the Solution Explorer, expand Home and expand Shared
  18. Double-click _Layout.cshtmnl to open the file
  19. 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 Home", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Payroll Evaluation", "TimeSheetEvaluation", "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>
  20. To execute the application, press Ctrl + F5

    Introduction to AngularJS Services

  21. Click the Payroll Evaluation link:

    Introduction to AngularJS Services

  22. Close the browser and return to your programming environment

Passing Arguments to a Service

A method of a service can use one or more parameters that would assist the service in performing its job. To prepare the method for an argument, add the name of a parameter to its parentheses. In the body of the method, ignore or use the parameter. Here is an example:

function announce() {
    this.validateUsername = function (uname) {
        if ((uname.length < 6) || (uname.length > 8)) {
            return "The username you are trying to create is not valid (too short or too long). Make sure your new user has 6 to 8 characters";
        }
        else {
            return "Thank you, your username has been validated."
        }
    }
}

When calling the method in the controller, make sure you pass an appropriate value for the argument. 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="appTimeSheet">
<script>
    var app = angular.module('appTimeSheet', []);
    app.service('tsService', announce);
    app.controller("TimeSheetController", present);

    function announce() {
        this.validateUsername = function (uname) {
            if ((uname.length < 6) || (uname.length > 8)) {
                return "The username you are trying to create is not valid (too short or too long). Make sure your new user has 6 to 8 characters";
            }
            else {
                return "Thank you, your username has been validated."
            }
        }
    }

    function present(tsService) {
        this.first = tsService.validateUsername("beth");
        this.second = tsService.validateUsername("stephen");
    }
</script>
<div ng-controller="TimeSheetController as tsc">
    <p><b>Error:</b> {{tsc.first}}</p>
    <p><b>Congratulations:</b> {{tsc.second}}</p>
</div>

</body>
</html>

Of course, you can define the function in its placeholder. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Kolo Bank</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="appBanking">
<script>
    var app = angular.module('appBanking', []);
    app.service('bankService', function announce() {
        this.validateUsername = function (pass) {
            if (pass.length < 10) {
                return "Invalid Credentials: Your password must have at least 10 characters";
            }
            else {
                return "Good Job: Your password meets our minimum requirements."
            }
        }
    });
    app.controller("TimeSheetController", present);

    function present(bankService) {
        var password = "P@s$word1";
        this.first = bankService.validateUsername(password);

        password = 'N0rthD@k8ta!!!'
        this.second = bankService.validateUsername(password);
    }
</script>

<div ng-controller="TimeSheetController as tsc">
    <p>{{tsc.first}}</p>
    <p>{{tsc.second}}</p>
</div>
</body>
</html>

In the same way, you can create a service-based method that uses as many parameters as you want. When creating the method, provide a name for each parameter. When calling the function, provide an appropriate value for the argument.

Practical LearningPractical Learning: Passing Arguments to a Service

  1. Access the TimeSheetEvaluation.js document and change it as follows:
    function calculateSalary() {
        function calculateRegularTime(time) {
            if (time <= 8.00)
                return time;
            else
                return 8.00;
        }
        function calculateOvertime(time) {
            if (time <= 8.00)
                return 0.00;
            else
                return time - 8.00;
        }
    
        this.monRegularTime = function (time) { return calculateRegularTime(time); }
        this.tueRegularTime = function (time) { return calculateRegularTime(time); }
        this.wedRegularTime = function (time) { return calculateRegularTime(time); }
        this.thuRegularTime = function (time) { return calculateRegularTime(time); }
        this.friRegularTime = function (time) { return calculateRegularTime(time); }
    
        this.monRegularPay = function (time, wage) { return calculateRegularTime(time) * wage; }
        this.tueRegularPay = function (time, wage) { return calculateRegularTime(time) * wage; }
        this.wedRegularPay = function (time, wage) { return calculateRegularTime(time) * wage; }
        this.thuRegularPay = function (time, wage) { return calculateRegularTime(time) * wage; }
        this.friRegularPay = function (time, wage) { return calculateRegularTime(time) * wage; }
    
        this.monOvertime = function (time) { return calculateOvertime(time); }
        this.tueOvertime = function (time) { return calculateOvertime(time); }
        this.wedOvertime = function (time) { return calculateOvertime(time); }
        this.thuOvertime = function (time) { return calculateOvertime(time); }
        this.friOvertime = function (time) { return calculateOvertime(time); }
    
        this.monOverPay = function (time, wage) { return calculateOvertime(time) * wage * 1.50; }
        this.tueOverPay = function (time, wage) { return calculateOvertime(time) * wage * 1.50; }
        this.wedOverPay = function (time, wage) { return calculateOvertime(time) * wage * 1.50; }
        this.thuOverPay = function (time, wage) { return calculateOvertime(time) * wage * 1.50; }
        this.friOverPay = function (time, wage) { return calculateOvertime(time) * wage * 1.50; }
    
        this.weeklySalary = function (wage, day1, day2, day3, day4, day5) {
            return (calculateRegularTime(day1) * wage) +
                (calculateRegularTime(day2) * wage) +
                (calculateRegularTime(day3) * wage) +
                (calculateRegularTime(day4) * wage) +
                (calculateRegularTime(day5) * wage) +
                (calculateOvertime(day1) * wage * 1.50) +
                (calculateOvertime(day2) * wage * 1.50) +
                (calculateOvertime(day3) * wage * 1.50) +
                (calculateOvertime(day4) * wage * 1.50) +
                (calculateOvertime(day5) * wage * 1.50);
        }
    }
    
    appPayrollApplication.service("timeSheetService", calculateSalary);
  2. Access the PayrollManagement.js document and change the controller as follows:
    var appPayrollApplication = angular.module("appPayroll", []);
    
    function processPayroll(timeSheetService) {
        this.prepare = function () {
            var sal = Number(this.HourlySalary || 0);
            var mon = Number(this.Monday       || 0);
            var tue = Number(this.Tuesday      || 0);
            var wed = Number(this.Wednesday    || 0);
            var thu = Number(this.Thursday     || 0);
            var fri = Number(this.Friday       || 0);
    
            this.MondayRegularTime = timeSheetService.monRegularTime(mon);
            this.TuesdayRegularTime = timeSheetService.tueRegularTime(tue);
            this.WednesdayRegularTime = timeSheetService.wedRegularTime(wed);
            this.ThursdayRegularTime = timeSheetService.thuRegularTime(thu);
            this.FridayRegularTime = timeSheetService.friRegularTime(fri);
    
            this.MondayRegularSalary = timeSheetService.monRegularPay(mon, sal);
            this.TuesdayRegularSalary = timeSheetService.tueRegularPay(tue, sal);
            this.WednesdayRegularSalary = timeSheetService.wedRegularPay(wed, sal);
            this.ThursdayRegularSalary = timeSheetService.thuRegularPay(thu, sal);
            this.FridayRegularSalary = timeSheetService.friRegularPay(fri, sal);
    
            this.MondayOvertime = timeSheetService.monOvertime(mon);
            this.TuesdayOvertime = timeSheetService.tueOvertime(tue);
            this.WednesdayOvertime = timeSheetService.wedOvertime(wed);
            this.ThursdayOvertime = timeSheetService.thuOvertime(thu);
            this.FridayOvertime = timeSheetService.friOvertime(fri);
    
            this.MondayOvertimeSalary = timeSheetService.monOverPay(mon, sal);
            this.TuesdayOvertimeSalary = timeSheetService.tueOverPay(tue, sal);
            this.WednesdayOvertimeSalary = timeSheetService.wedOverPay(wed, sal);
            this.ThursdayOvertimeSalary = timeSheetService.thuOverPay(thu, sal);
            this.FridayOvertimeSalary = timeSheetService.friOverPay(fri, sal);
    
            this.NetPay = timeSheetService.weeklySalary(sal, mon, tue, wed, thu, fri);
        }
    }
    
    appPayrollApplication.controller("PayrollController", processPayroll);
  3. Access the TimeSheetEvaluation.cshtml document and change it as follows:
    @{
        ViewBag.Title = "Payroll Evaluation";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <div ng-app="appPayroll">
        <h2 class="common-font text-center bold">Payroll Evaluation</h2>
        <hr />
    
        <div class="delimiter" ng-controller="PayrollController as pay">
            <form name="TimeSheetEvaluation" method="post">
                <table>
                    <tr>
                        <td class="large-text bold">Hourly Salary:</td>
                        <td colspan="5"><input type="text" class="form-control ng-model" ng-model="pay.HourlySalary" /></td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                    </tr>
                </table>
    
                <table class="table table-striped">
                    <tr>
                        <td>&nbsp;</td>
                        <td class="bold text-center">Monday</td>
                        <td class="bold text-center">Tuesday</td>
                        <td class="bold text-center">Wednesday</td>
                        <td class="bold text-center">Thursday</td>
                        <td class="bold text-center">Friday</td>
                    </tr>
                    <tr>
                        <td class="bold">Time Worked:</td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Monday" ng-change="pay.prepare()" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Tuesday" ng-change="pay.prepare()" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Wednesday" ng-change="pay.prepare()" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Thursday" ng-change="pay.prepare()" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Friday" ng-change="pay.prepare()" /></td>
                    </tr>
                    <tr>
                        <td class="bold">Regular Time:</td>
                        <td>{{pay.MondayRegularTime | number: 2}}</td>
                        <td>{{pay.TuesdayRegularTime | number: 2}}</td>
                        <td>{{pay.WednesdayRegularTime | number: 2}}</td>
                        <td>{{pay.ThursdayRegularTime | number: 2}}</td>
                        <td>{{pay.FridayRegularTime | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Regular Salary:</td>
                        <td>{{pay.MondayRegularSalary | number: 2}}</td>
                        <td>{{pay.TuesdayRegularSalary | number: 2}}</td>
                        <td>{{pay.WednesdayRegularSalary | number: 2}}</td>
                        <td>{{pay.ThursdayRegularSalary | number: 2}}</td>
                        <td>{{pay.FridayRegularSalary | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Overtime:</td>
                        <td>{{pay.MondayOvertime | number: 2}}</td>
                        <td>{{pay.TuesdayOvertime | number: 2}}</td>
                        <td>{{pay.WednesdayOvertime | number: 2}}</td>
                        <td>{{pay.ThursdayOvertime | number: 2}}</td>
                        <td>{{pay.FridayOvertime | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Overtime Salary:</td>
                        <td>{{pay.MondayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.TuesdayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.WednesdayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.ThursdayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.FridayOvertimeSalary | number: 2}}</td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td class="bold">Weekly Salary:</td>
                        <td>{{pay.NetPay | number: 2}}</td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
  4. To test the form, press Ctrl + F5

    Passing Arguments to a Service

  5. In the text boxes, enter the following values:
    Hourly Salary: 16.36
    Monday:         9.50
    Tuesday:        8.00
    Wednesday:      7.00
    Thursday:      10.50
    Friday:         6.50

    Passing Arguments to a Service

    Passing Arguments to a Service

    Passing Arguments to a Service

  6. Close the browser and return to your programming environment

Using Many Services

Introduction

Just like an application can use many controllers, a controller can use many services. After creating the services, to use them in a controller, pass them as arguments to the constructor of the intended controller. As always, the arguments must be separated by commas. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Watts' A Loan</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<h1>Watts' A Loan</h1>

<script type="text/javascript">
    var appWAL = angular.module("appWattsALoan", []);

    function compInterestCalculations() {

    }
    appWAL.service('compoundInterest', compInterestCalculations);

    function machineIdentification() {

    }
    appWAL.service('businessMachines', compInterestCalculations);

    function manage(compoundInterest, businessMachines) {

    }
    appWAL.controller("LoansController", manage);
</script>
</body>
</html>

ApplicationPractical Learning: Introducing Multiple Services

  1. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File.
  2. Type PayCheckEvaluation as the name of the file
  3. Click OK
  4. In the empty document, type the following code:
    function evaluateTaxes() {
    
    }
    
    appPayrollApplication.service('payCheckService', evaluateTaxes);
  5. Click the BundleConfig.cs tab to access the document and change it as follows:
    using System.Web.Optimization;
    
    namespace PayrollPreparation2
    {
        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/PayrollManagement.js",
                            "~/Scripts/TimeSheetEvaluation.js",
                            "~/Scripts/PayCheckEvaluation.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"));
            }
        }
    }
  6. Access the PayrollManagement.js document and change it as follows:
    var appPayrollApplication = angular.module("appPayroll", []);
    
    function processPayroll(timeSheetService, payCheckService) {
        this.prepare = function () {
    
            . .  . No Change
    
        }
    }
    
    appPayrollApplication.controller("PayrollController", processPayroll);

Accessing Multiple Services of a Controller

If your controller is using many services, you can use the same steps to pass the service to the controller and access its job in a webpage. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Watts' A Loan</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<script type="text/javascript">
    var appWAL = angular.module("appWattsALoan", []);

    function loanIdentification() {
        this.reason = "The reason or subject of the loan must be identified.";
    }
    appWAL.service('loanSubject', loanIdentification);

    function compInterestCalculations() {
        this.introduction = "This service is used to evaluate a loan using its principal, an interest rate, and the length of the loan";
    }
    appWAL.service('compoundInterest', compInterestCalculations);

    function manage(compoundInterest, loanSubject) {
        this.presentation = compoundInterest.introduction;
        this.justification = loanSubject.reason;
    }
    appWAL.controller("LoansController", manage);
</script>

<h1>Watts' A Loan</h1>

<div ng-app="appWattsALoan">
    <div ng-controller="LoansController as lc">
        <p>Introduction: {{lc.presentation}}</p>
        <p>{{lc.justification}}</p>
    </div>
</div>
<form name="LoanEvaluation" method="get">

</form>
</body>
</html>

Notmally, you usually use different services so that each can take care of a particular aspect of the project. In fact, if a service performs many or long operations, you can create it in iits own file.

Practical LearningPractical Learning: Accessing Multiple Services

  1. Access the PayCheckEvaluation.js document and change its function as follows:
    function evaluateTaxes() {
        var allowanceRate = 77.90;
    
        this.withheldAllowances = function (exmpt) { return allowanceRate * exmpt; }
        this.taxedAmount = function (sal, exmpt) { return sal - (allowanceRate * exmpt); };
    
        this.taxesBasedOnStatus = function (sal, exmpt) {
            var withheldAmount = 0;
            var taxableSalary = sal - (allowanceRate * exmpt);
    
            return withheldAmount = (taxableSalary - 44) * 10 / 100;
        }
    }
    
    appPayrollApplication.service('payCheckService', evaluateTaxes);
  2. Access the PayrollManagement.js document and change it as follows:
    var appPayrollApplication = angular.module("appPayroll", []);
    
    function processPayroll(timeSheetService, payCheckService) {
        this.prepare = function () {
            var sal = Number(this.HourlySalary || 0);
            var mon = Number(this.Monday       || 0);
            var tue = Number(this.Tuesday      || 0);
            var wed = Number(this.Wednesday    || 0);
            var thu = Number(this.Thursday     || 0);
            var fri = Number(this.Friday       || 0);
    
            this.MondayRegularTime = timeSheetService.monRegularTime(mon);
            this.TuesdayRegularTime = timeSheetService.tueRegularTime(tue);
            this.WednesdayRegularTime = timeSheetService.wedRegularTime(wed);
            this.ThursdayRegularTime = timeSheetService.thuRegularTime(thu);
            this.FridayRegularTime = timeSheetService.friRegularTime(fri);
    
            this.MondayRegularSalary = timeSheetService.monRegularPay(mon, sal);
            this.TuesdayRegularSalary = timeSheetService.tueRegularPay(tue, sal);
            this.WednesdayRegularSalary = timeSheetService.wedRegularPay(wed, sal);
            this.ThursdayRegularSalary = timeSheetService.thuRegularPay(thu, sal);
            this.FridayRegularSalary = timeSheetService.friRegularPay(fri, sal);
    
            this.MondayOvertime = timeSheetService.monOvertime(mon);
            this.TuesdayOvertime = timeSheetService.tueOvertime(tue);
            this.WednesdayOvertime = timeSheetService.wedOvertime(wed);
            this.ThursdayOvertime = timeSheetService.thuOvertime(thu);
            this.FridayOvertime = timeSheetService.friOvertime(fri);
    
            this.MondayOvertimeSalary = timeSheetService.monOverPay(mon, sal);
            this.TuesdayOvertimeSalary = timeSheetService.tueOverPay(tue, sal);
            this.WednesdayOvertimeSalary = timeSheetService.wedOverPay(wed, sal);
            this.ThursdayOvertimeSalary = timeSheetService.thuOverPay(thu, sal);
            this.FridayOvertimeSalary = timeSheetService.friOverPay(fri, sal);
    
            this.NetPay = timeSheetService.weeklySalary(sal, mon, tue, wed, thu, fri);
    
            var dependents = Number(this.exemptions || 0);
    
            this.grossSalary = timeSheetService.weeklySalary(sal, mon, tue, wed, thu, fri);
            this.allowances = payCheckService.withheldAllowances(dependents)
            this.taxableGrossWages = payCheckService.taxedAmount(this.NetPay, dependents);
            this.federalIncomeTax = payCheckService.taxesBasedOnStatus(this.NetPay, dependents);
        }
    }
    
    appPayrollApplication.controller("PayrollController", processPayroll);
  3. Access the TimeSheetEvaluation.cshtml document and change it as follows:
    @{
        ViewBag.Title = "Payroll Evaluation";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <div ng-app="appPayroll">
        <h2 class="common-font text-center bold">Payroll Evaluation</h2>
        <hr />
    
        <div class="delimiter" ng-controller="PayrollController as pay">
            <form name="TimeSheetEvaluation" method="post">
                <table>
                    <tr>
                        <td class="large-text bold">Hourly Salary:</td>
                        <td colspan="5"><input type="text" class="form-control ng-model" ng-model="pay.HourlySalary" /></td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                    </tr>
                </table>
    
                <table class="table table-striped">
                    <tr>
                        <td>&nbsp;</td>
                        <td class="bold text-center">Monday</td>
                        <td class="bold text-center">Tuesday</td>
                        <td class="bold text-center">Wednesday</td>
                        <td class="bold text-center">Thursday</td>
                        <td class="bold text-center">Friday</td>
                    </tr>
                    <tr>
                        <td class="bold">Time Worked:</td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Monday" ng-change="pay.prepare()" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Tuesday" ng-change="pay.prepare()" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Wednesday" ng-change="pay.prepare()" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Thursday" ng-change="pay.prepare()" /></td>
                        <td><input type="text" class="form-control ng-model" ng-model="pay.Friday" ng-change="pay.prepare()" /></td>
                    </tr>
                    <tr>
                        <td class="bold">Regular Time:</td>
                        <td>{{pay.MondayRegularTime | number: 2}}</td>
                        <td>{{pay.TuesdayRegularTime | number: 2}}</td>
                        <td>{{pay.WednesdayRegularTime | number: 2}}</td>
                        <td>{{pay.ThursdayRegularTime | number: 2}}</td>
                        <td>{{pay.FridayRegularTime | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Regular Salary:</td>
                        <td>{{pay.MondayRegularSalary | number: 2}}</td>
                        <td>{{pay.TuesdayRegularSalary | number: 2}}</td>
                        <td>{{pay.WednesdayRegularSalary | number: 2}}</td>
                        <td>{{pay.ThursdayRegularSalary | number: 2}}</td>
                        <td>{{pay.FridayRegularSalary | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Overtime:</td>
                        <td>{{pay.MondayOvertime | number: 2}}</td>
                        <td>{{pay.TuesdayOvertime | number: 2}}</td>
                        <td>{{pay.WednesdayOvertime | number: 2}}</td>
                        <td>{{pay.ThursdayOvertime | number: 2}}</td>
                        <td>{{pay.FridayOvertime | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Overtime Salary:</td>
                        <td>{{pay.MondayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.TuesdayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.WednesdayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.ThursdayOvertimeSalary | number: 2}}</td>
                        <td>{{pay.FridayOvertimeSalary | number: 2}}</td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td class="bold">Weekly Salary:</td>
                        <td>{{pay.NetPay | number: 2}}</td>
                    </tr>
                </table>
    
                <table class="table table-striped">
                    <tr>
                        <td class="left-column bold">Gross Salary:</td>
                        <td>{{pay.grossSalary | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Exemptions:</td>
                        <td>
                            <input type="number" class="form-control ng-model"
                                   ng-model="pay.exemptions" ng-change="pay.prepare()" />
                        </td>
                    </tr>
                    <tr>
                        <td class="bold">Allowances:</td>
                        <td>{{pay.allowances | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Taxable Gross Wages:</td>
                        <td>{{pay.taxableGrossWages | number: 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Federal Income Tax:</td>
                        <td>{{pay.federalIncomeTax | number: 2}}</td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
  4. To execute, on the main menu, click Debug -> Start Without Debugging

    Accessing Multiple Services

  5. In the text boxes, type the following values:
    Hourly Salary: 16.38
    Monday:         7.50
    Tuesday:        9.50
    Wednesday:      8
    Thursday:      10
    Friday:         9
    Exemptions:     1

    Accessing Multiple Services

    Accessing Multiple Services

    Accessing Multiple Services

    Accessing Multiple Services

  6. Close the browser and return to your programming environment
  7. Close your programming environment

Previous Copyright © 2017-2022, FunctionX Next