Overview of AngularJS Services

Introduction to Built-In Services

Before creating services for your projects, AngularJS provides many built-in services that you can directly use in your code. Of course, the services provide different functionalities. Each service is created as, or represents, an object. This means that the services may have properties and methods. Some services are AngularJS adaptation of HTML (the DOM). Some others are proper to AngularJS. The names of the built-in services start with $ followed by one or more letters. To use a service, you must apply it to a component that needs it.

Practical LearningPractical Learning: Introducing Built-In Services

  1. Start Microsoft Visual Studio
  2. To start a new website, on the main menu, click File -> New -> Project...
  3. In the New Project dialog box, click ASP.NET Web Application (.NET Framework)
    Change the project Name to TireDirect1
  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 TireDirect1 and click Manage NuGet Packages...
  7. Click the Browser button.
    Do a search on AngularJS
  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. In the Solution Explorer, right-click Content -> Add -> New Item...
  11. In the Add New Item dialog box, click Style Sheet
  12. Change the Name of the file to TireDirect
  13. Click Add
  14. In the document, create the following styles:
    body {
        background-color: #F2EDDA;
    }
    .bold                  { font-weight:      600;    }
    .installation-contents { margin:           auto;
                             width:            340px;  }
    .main-title            { color:            maroon; }
    .short-text            { width:            60px;   }
    .medium-text           { width:            80px;   }
    .left-col              { width:            120px;  }
    .large-col             { width:            180px;  }
    .group-box             { border-radius:    5px;
                             padding-left:     20px;
                             padding-right:    20px;
                             width:            350px;
                             background-color: #E0DCCC;
                             border:           2px solid #800000; }
    .group-box legend      { border-radius:    5px;
                             margin-left:      10px;
                             font-size:        16px;
                             width:            235px;
                             color:            #E5DDAF;
                             background-color: #6B2C3D;
                             padding:          5px 15px;
                             box-shadow:       0 0 0 5px #E5DDAF; }
    .tbl-installations      { margin-bottom:   15px;
                              width:           100%;
                              margin-left:     15px; }
    .common-font            { font-family:     Georgia, Garamond, 'Times New Roman', serif; }
  15. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  16. Change the document as follows:
    using System.Web.Optimization;
    
    namespace TireDirect1
    {
        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"));
    
                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/TireDirect.css"));
            }
        }
    }
  17. In the Solution Explorer, expand Controller and double-click HomeController.cs
  18. In the class, create a method named TireInstallationSalary as follows:
    using System.Web.Mvc;
    
    namespace TireDirect1.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 TireInstallationSalary()
            {
                return View();
            }
        }
    }
  19. In the Solution Explorer, expand Home and expand Shared
  20. Double-click _Layout.cshtmnl to open the file
  21. 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>Tire Direct :: @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("Tire Direct Home", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Tire Installation Salary", "TireInstallationSalary", "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">&copy; @DateTime.Now.Year - Tire Direct</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  22. In the Solution Explorer, expand Views
  23. Right-click Home -> Add -> View...
  24. Type TireInstallationSalary as the name of the view
  25. Click Add
  26. Change the document as follows:
    @{
        ViewBag.Title = "Tire Installation Salary";
    }
    
    <h2 class="text-center common-font bold main-title">Tire Installation Salary</h2>
    
    @Scripts.Render("~/bundles/jquery")
    
    <div class="installation-contents common-font" ng-app>
        <form name="TireInstallation" method="post">
            <table>
                <tr>
                    <td class="bold">Base Hourly Rate:</td>
                    <td><input type="number" class="form-control medium-text" ng-model="baseHourlyRate" /></td>
                    <td class="bold">/Hr</td>
                </tr>
                <tr>
                    <td class="bold">Base Tire Rate:</td>
                    <td><input type="number" class="form-control medium-text" ng-model="baseTireRate" /></td>
                    <td class="bold">/Tire</td>
                </tr>
            </table>
            <hr />
            <fieldset class="group-box">
                <legend>Number of Tires Installed on</legend>
                <table class="tbl-installations">
                    <tr>
                        <td class="bold left-col">Day</td>
                        <td class="bold">Tires</td>
                        <td class="bold">Salary</td>
                    </tr>
                    <tr>
                        <td class="bold">Monday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="MondayInstallations" /></td>
                        <td>{{MondayInstallations * baseTireRate | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Tuesday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="TuesdayInstallations" /></td>
                        <td>{{TuesdayInstallations * baseTireRate | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Wednesday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="WednesdayInstallations" /></td>
                        <td>{{WednesdayInstallations * baseTireRate | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Thursday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="ThursdayInstallations" /></td>
                        <td>{{ThursdayInstallations * baseTireRate | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Friday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="FridayInstallations" /></td>
                        <td>{{FridayInstallations * baseTireRate | number : 2}}</td>
                    </tr>
                </table>
                <hr />
                <table>
                    <tr>
                        <td class="left-col">&nbsp;</td>
                        <td class="left-col bold text-center">Net Pay:</td>
                        <td class="text-right">{{(MondayInstallations * baseTireRate) + (TuesdayInstallations * baseTireRate) + (WednesdayInstallations * baseTireRate) + (ThursdayInstallations * baseTireRate) + (FridayInstallations * baseTireRate) | number : 2}}</td>
                    </tr>
                </table>
            </fieldset>
        </form>
    </div>
  27. To execute the application, press Ctrl + F5:

    Introduction to Built-In Services

  28. In the text boxes, enter the following values:
    Base Hourly Rate:  10.05
    Base Tire Rate:     0.92
    Monday:           112
    Tuesday:           68
    Wednesday:         84
    Thursday:          47
    Friday:            73

    Introduction to Built-In Services

    Introduction to Built-In Services

    Introduction to Built-In Services

  29. Close the browser and return to your programming environment
  30. To start an AngularJS controller, in the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  31. Type SalaryEvaluation as the name of the file
  32. Click OK
  33. Change the document as follows:
    var appTireInstallation = angular.module('tireInstallation', []);
    
    function evaluate() {
    
    }
    
    appTireInstallation.controller("TireInstallationController", evaluate);
  34. Click the BundleConfig.cs tab to access the file
  35. Change the document as follows:
    using System.Web.Optimization;
    
    namespace TireDirect1
    {
        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/SalaryEvaluation.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/TireDirect.css"));
            }
        }
    }

Watching Code

In application programming, a watch is a sub-program that knows (is aware of) the variables, the objects (the classes, their properties, their constants, and their methods), and expressions in order to monitor them. Among the jobs of a watch is to be aware when something changes, such as when a file is opened, when an existing file changes, when an expression changes, etc. In other words, a watch is used to monitor code execution.

To support watches, AngularJS provides a service named $watch.

Scoping Data

Introduction

You may already know that, in an ASP.NET MVC project, to let a controller class be able to send values to a view, the Controller class, which is the parent of the controller classes, is equipped with a property named ViewBag. You can add (or attach) any property to that variable. To let you exchange values between an AngularJS object (such as a controller, a service, or an event) and the HTML tags of a webpage (that is, the tags that use AngularJS directives, such as webcontrols or {{}} placeholders), AngularJS provides special services named scopes.

Introduction to Scopes

As you may be aware by your current knowledge of application programming, a scope is the area in which a variable or an object is available, such as inside a method of a class or a webpage. To provide an object that can monitor the area of influence of a variable or object, AngularJS provides a service named $rootScope. To further control the areas of influence of variables and objects, other scopes can be created from $rootScope. To let you create a child scope, the $rootScope object provides a method named $new.

Introduction to the Scope Service

To allow an AngujarJS component, such as a controller, to exchange data with a webpage (a view), AngularJS provides a service named $scope. This service is derived from the $rootScope service. To use the $rootScope or the $scope service, first pass it as argument to the function defined in (or for) a controller. Here is an example:

function calculate($scope) {

}

angular
    .module('customized', [])
    .controller('EmployeesController', calculate);

In the body of the function, you can declare a var variable and initialize it with the $rootScope or the $scope object. Here is an example:

var app = angular.module('rosh', []);
    
app.controller('GradesReportsController', function ($rootScope) {
    var reports = $rootScope;
});

You can use the $rootScope or the $scope object the same way you would use ViewBag in a method of an ASP.NET MVC controller class. That is, apply a desired property to it, with a period between them. This would be done as follows:

var appModule = angular.module('toysModule', []);
appModule.controller('ToysController', function ($scope) {
    $scope.toyName;
});

If you had declared a variable for the $rootScope or the $scope object, you can attach the property to that variable. Here is an example:

var app = angular.module('rosh', []);
    
app.controller('GradesReportsController', function ($rootScope) {
    var reports = $rootScope;

    reports.title
});

Adding a Property to a Scope

The primary purpose of the $scope object is to serve as an intermediary between the HTML tags of a section where AngularJS is used and an AngularJS controller. Therefore, in the body of the function, you can access each webcontrol by its ng-model name using the $scope object the same way we were using the this object in a service.

To pass values from a controller to a view, you can set the desired value to a property attached to the $rootScope or the $scope object. This is done by assigning a value. In the webpage, access the property by its name. Here is an example:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>

<div ng-app="customized" ng-controller="EmployeesController">
    @using (Html.BeginForm())
    {
        <p>Yearly Salary: <input type="text" ng-model="yearly" /></p>
    }
</div>

<script>
    function calculate($scope) {
        $scope.yearly = 64800;
    }

    angular
        .module('customized', [])
        .controller('EmployeesController', calculate);
</script>

You can also access the value using the ng-bind directive included in a text-based or neutral element such as P, PRE, or SPAN. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Red Oak High School</title>
<script src="Scripts/angular.js"></script>
</head>
<body ng-app="rosh">
    <div ng-controller="GradesReportsController">
        <p>Report Title: <span ng-bind="title"></span></p>
    </div>

<script>
    var app = angular.module('rosh', []);
    
    app.controller('GradesReportsController', function ($rootScope) {
        var reports = $rootScope;

        reports.title = 'School Grades Reports';
    });
</script>
</body>
</html>

You can also involve the $rootScope or the $scope object appended the ng-model name in any expression of your choice. Here are examples:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>

<div ng-app="customized" ng-controller="EmployeesController">
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td>Yearly Salary:</td>
                <td><input type="text" ng-model="yearly" /></td>
            </tr>
            <tr>
                <td>Monthly Salary:</td>
                <td><input type="text" ng-model="monthly" /></td>
            </tr>
        </table>
    }
</div>

<script>
    function calculate($scope) {
        $scope.yearly = 64800;
        $scope.monthly = $scope.yearly / 12;
    }

    angular
        .module('customized', [])
        .controller('EmployeesController', calculate);
</script>

Remember that you can declare one or more variables in the function of a service or controller. If you want to send the value of a variable declared in a controller-based function to a webpage, you can assign the variable to the $scope object appended with the intended ng-model control. Here is an example:

@{
    ViewBag.Title = "Exercise";
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>

<h2>Exercise</h2>

<div ng-app="exercise">
    <p ng-controller="WisdomController">Wisdom: {{popular}}</p>
</div>

<script>
    function say($scope) {
        var quote = "Absence of evidence is not evidence of absence.";
        $scope.popular = quote;
    }
    angular.module('exercise', []).controller('WisdomController', say);
</script>

Practical LearningPractical Learning: Initializing a Scoped Property

  1. Change the SalaryEvaluation.js document as follows:
    var appTireInstallation = angular.module('tireInstallation', []);
    
    function evaluate($scope) {
        var hourlyRate = 10.17;
        var tirePay = 0.96;
        var monWork = 81, tueWork = 47, wedWork = 97, thuWork = 59, friWork = 93;
    
        var monPay = monWork * tirePay;
        var tuePay = tueWork * tirePay;
        var wedPay = wedWork * tirePay;
        var thuPay = thuWork * tirePay;
        var friPay = friWork * tirePay;
        var totalPay = monPay + tuePay + wedPay + thuPay + friPay;
    
        $scope.FridaySalary = friPay;
        $scope.MondaySalary = monPay;
        $scope.baseTireRate = tirePay;
        $scope.TuesdaySalary = tuePay;
        $scope.ThursdaySalary = thuPay;
        $scope.WednesdaySalary = wedPay;
        $scope.baseHourlyRate = hourlyRate;
        $scope.MondayInstallations = monWork;
        $scope.FridayInstallations = friWork;
        $scope.ThursdayInstallations = thuPay;
        $scope.TuesdayInstallations = tueWork;
        $scope.ThursdayInstallations = thuWork;
        $scope.WednesdayInstallations = wedWork;
        $scope.TireInstallationsSalary = totalPay;
    }
    
    appTireInstallation.controller('TireInstallationsController', evaluate);
  2. Access the TireInstallationSalary.cshtml document and change it as follows:
    @{
        ViewBag.Title = "Tire Installation Salary";
    }
    
    <h2 class="text-center common-font bold main-title">Tire Installation Salary</h2>
    
    @Scripts.Render("~/bundles/jquery")
    
    <div class="installation-contents common-font" ng-app="tireInstallation">
        <form name="SalaryEvaluation" method="post" ng-controller="TireInstallationsController">
            <table>
                <tr>
                    <td class="bold">Base Hourly Rate:</td>
                    <td><input type="number" class="form-control medium-text" ng-model="baseHourlyRate" /></td>
                    <td class="bold">/Hr</td>
                </tr>
                <tr>
                    <td class="bold">Base Tire Rate:</td>
                    <td><input type="number" class="form-control medium-text" ng-model="baseTireRate" /></td>
                    <td class="bold">/Tire</td>
                </tr>
            </table>
            <hr />
            <fieldset class="group-box">
                <legend>Number of Tires Installed on</legend>
                <table class="tbl-installations">
                    <tr>
                        <td class="bold left-col">Day</td>
                        <td class="bold">Tires</td>
                        <td class="bold">Salary</td>
                    </tr>
                    <tr>
                        <td class="bold">Monday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="MondayInstallations" /></td>
                        <td>{{MondaySalary | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Tuesday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="TuesdayInstallations" /></td>
                        <td>{{TuesdaySalary | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Wednesday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="WednesdayInstallations" /></td>
                        <td>{{WednesdaySalary | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Thursday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="ThursdayInstallations" /></td>
                        <td>{{ThursdaySalary | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Friday:</td>
                        <td><input type="number" class="form-control short-text" ng-model="FridayInstallations" /></td>
                        <td>{{FridaySalary | number : 2}}</td>
                    </tr>
                </table>
                <hr />
                <table>
                    <tr>
                        <td class="left-col">&nbsp;</td>
                        <td class="left-col bold text-center">Net Pay:</td>
                        <td class="text-right">{{TireInstallationsSalary | number : 2}}</td>
                    </tr>
                </table>
            </fieldset>
        </form>
    </div>
  3. To execute the application, press Ctrl + F5:

    Initializing a Scoped Property

  4. Close the browser and return to your programming environment

Getting the Value of a Scoped Property

Using the $scope object, you can get (retrieve) the value of an HTML tag such as a webcontrol from a form. To do this, in the controller, type $scope. followed by the ng-model name of the controller. You can then assign that expression to a local variable. Here is an example:

@{
    ViewBag.Title = "Employee Record";
}

<h2 class="text-center">Employee Record</h2>

<form name="EmployeeApplication" method="post" ng-app="employeeModule">
    <p ng-controller="EmployeeController"><label for="FirstName">First Name:</label>
       <input type="text" id="FirstName" ng-model="FirstName" /><br />
    {{FirstName}}</p>
</form>

<script>
    function hire($scope) {
        first = $scope.FirstName;
    }

    var emplModule = angular.module('employeeModule', []);
    emplModule.controller('EmployeeController', hire);

</script>

Scoping a Controller

Introduction

If you want to access a controller in a webpage, you can add a function to it. This is done by nesting an anonymous function in the constructor of a controller. To proceed, attach a property to the $scope object and assign the function to that property. You can then call that function in a webpage, such as in an event. To access the controller, that is, to call the function, use the name of the property you had attached to the $scope object and add the parentheses.

Practical LearningPractical Learning: Passing Values to a Controller

  1. Access the SalaryEvaluation.js document and change it as follows:
    var appTireInstallation = angular.module('tireInstallation', []);
    
    function evaluate($scope) {
        $scope.transmit = function () {
            var payRate = 0.00;
    
            var hourlyRate = Number($scope.baseHourlyRate || 0);
            var tirePay = Number($scope.baseTireRate || 0);
            var monWork = Number($scope.MondayInstallations || 0);
            var tueWork = Number($scope.TuesdayInstallations || 0);
            var wedWork = Number($scope.WednesdayInstallations || 0);
            var thuWork = Number($scope.ThursdayInstallations || 0);
            var friWork = Number($scope.FridayInstallations || 0);
    
            var dailySalary = hourlyRate * 8.00;
    
            var dInstallationMondayPay = monWork * tirePay;
            var dInstallationTuesdayPay = tueWork * tirePay;
            var dInstallationWednesdayPay = wedWork * tirePay;
            var dInstallationThursdayPay = thuWork * tirePay;
            var dInstallationFridayPay = friWork * tirePay;
    
            var netPayMonday = dInstallationMondayPay;
            var netPayTuesday = dInstallationTuesdayPay;
            var netPayWednesday = dInstallationWednesdayPay;
            var netPayThursday = dInstallationThursdayPay;
            var netPayFriday = dInstallationFridayPay;
    
            if (monWork == 0) { netPayMonday = 0; }
            else {
                if (dInstallationMondayPay < dailySalary) { netPayMonday = dailySalary; }
            }
    
            if (tueWork == 0) { netPayTuesday = 0; }
            else {
                if (dInstallationTuesdayPay < dailySalary) { netPayTuesday = dailySalary; }
            }
    
            if (wedWork == 0) { netPayWednesday; }
            else {
                if (dInstallationWednesdayPay < dailySalary) { netPayWednesday = dailySalary; }
            }
    
            if (thuWork == 0) { netPayThursday = 0; }
            else {
                if (dInstallationThursdayPay < dailySalary) { netPayThursday = dailySalary; }
            }
    
            if (friWork == 0) { netPayFriday = 0; }
            else {
                if (dInstallationFridayPay < dailySalary) { netPayFriday = dailySalary; }
            }
    
            $scope.FridaySalary = netPayFriday;
            $scope.MondaySalary = netPayMonday;
            $scope.TuesdaySalary = netPayTuesday;
            $scope.ThursdaySalary = netPayThursday;
            $scope.WednesdaySalary = netPayWednesday;
    
            $scope.TireInstallationsSalary = netPayMonday + netPayTuesday + netPayWednesday + netPayThursday + netPayFriday;
        }
    }
    
    appTireInstallation.controller('TireInstallationsController', evaluate);
  2. Access the TireInstallationSalary.cshtml document and change it as follows:
    @{
        ViewBag.Title = "Tire Installation Salary";
    }
    
    <h2 class="text-center common-font bold main-title">Tire Installation Salary</h2>
    
    @Scripts.Render("~/bundles/jquery")
    
    <div class="installation-contents common-font" ng-app="tireInstallation">
        <form name="TireInstallation" method="post" ng-controller="TireInstallationsController">
            <table>
                <tr>
                    <td class="bold">Base Hourly Rate:</td>
                    <td><input type="number" class="form-control medium-text" ng-model="baseHourlyRate" /></td>
                    <td class="bold">/Hr</td>
                </tr>
                <tr>
                    <td class="bold">Base Tire Rate:</td>
                    <td><input type="number" class="form-control medium-text" ng-model="baseTireRate" /></td>
                    <td class="bold">/Tire</td>
                </tr>
            </table>
            <hr />
            <fieldset class="group-box">
                <legend>Number of Tires Installed on</legend>
                <table class="tbl-installations">
                    <tr>
                        <td class="bold left-col">Day</td>
                        <td class="bold">Tires</td>
                        <td class="bold">Salary</td>
                    </tr>
                    <tr>
                        <td class="bold">Monday:</td>
                        <td><input type="number" class="form-control short-text"
                                   ng-model="MondayInstallations" ng-change="transmit()" /></td>
                        <td>{{MondaySalary | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Tuesday:</td>
                        <td><input type="number" class="form-control short-text"
                                   ng-model="TuesdayInstallations" ng-change="transmit()" /></td>
                        <td>{{TuesdaySalary | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Wednesday:</td>
                        <td><input type="number" class="form-control short-text"
                                   ng-model="WednesdayInstallations" ng-change="transmit()" /></td>
                        <td>{{WednesdaySalary | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Thursday:</td>
                        <td><input type="number" class="form-control short-text"
                                   ng-model="ThursdayInstallations" ng-change="transmit()" /></td>
                        <td>{{ThursdaySalary | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold common-font">Friday:</td>
                        <td><input type="number" class="form-control short-text"
                                   ng-model="FridayInstallations" ng-change="transmit()" /></td>
                        <td>{{FridaySalary | number : 2}}</td>
                    </tr>
                </table>
                <hr />
                <table>
                    <tr>
                        <td class="left-col">&nbsp;</td>
                        <td class="left-col bold text-center">Net Pay:</td>
                        <td class="text-right">{{TireInstallationsSalary | number : 2}}</td>
                    </tr>
                </table>
            </fieldset>
        </form>
    </div>
  3. To execute the application, on the main menu, click Debug -> Start Without Debugging
  4. Set the values of the text boxes as follows:
    Base Hourly Rate: 11.25
    Base Tire Rate:   0.98
    Monday:           92
    Tuesday:          46
    Wednesday:        118
    Thursday:         63
    Friday:           105

    Switching a String

    Switching a String

    Switching a String

  5. Close the browser and return to your programming environment

Scoping a Function

If you need to perform an action in a controller, you can create and attach a function to a $scope object. To do this, define a function and assign it to a property attached to the $scope object. Here is an example:

var appExercise = angular.module('appMovies', []);
appExercise.controller('QuotationsController', speak);

function speak ($scope) {
        $scope.cite = function () {
            . . .
        }
}

Although not required, you can name the function if you want. Here is an example:

var appExercise = angular.module('appMovies', []);
appExercise.controller('QuotationsController', bring);

function speak ($scope) {
        $scope.cite = function monologue() {
            . . .
        }
}

As another option (nor required), you can pass the $scope object as argument:

var appExercise = angular.module('appMovies', []);
appExercise.controller('QuotationsController', bring);

function speak ($scope) {
        $scope.cite = function monologue($scope) {
            . . .
        }
}

To call the method in a webpage, use its name and apply the parentheses to it. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Movies Quotes</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body ng-app="appMovies" ng-controller="QuotationsController">
<h1>Movies Quotes</h1>

<p>{{cite()}}</p>

<script type="text/javascript">
    var appExercise = angular.module('appMovies', []);
    appExercise.controller('QuotationsController', speak);

    function speak ($scope) {
        $scope.cite = function monologue($scope) {
            return "The days of investigative reporting are over, Lauren. " +
                   "The news isn't news anymore. It's as dead as the typewriter " +
                   "I used to write it on. Corporate America is running the show now. " +
                   "And their news agenda is free trade, globalisation and entertainment. " +
                   "That's our glorious future." +
                   "--Bordertown--";
        }
    }
</script>
</body>
</html>

Passing Arguments to a Scope

If you decide to perform some actions directly on a scope, you can provide one or more values to it to assist it. To do this, in the parentheses of a method attached to the scope, provide one or more names of parameters. In the body of the method, use the parameters as you see fit. Here is an example:

var appPayroll = angular.module("appPayroll", []);
appPayroll.controller("PayrollController", calculate);

function calculate($scope) {
    $scope.totalPay = function (x, y) {
        return x + y;
    }
}

When calling the method, use its name, add the parentheses, and pass the appropriate argument(s).

Practical LearningPractical Learning: Passing Arguments to a Scope

  1. To start a new website, on the main menu, click File -> New -> Project...
  2. In the New Project dialog box, click ASP.NET Web Application (.NET Framework)
    Change the project Name to PayrollPreparation3
  3. Click OK
  4. In the Solution Explorer, right-click PayrollPreparation3 and click Manage NuGet Packages...
  5. Click the Browser button.
    Do a search on AngularJS
  6. In the list, click angularjs
  7. In the middle-right frame, click Install. If a dialog box comes up, read it and click OK
  8. In the Solution Explorer, right-click Content -> Add -> Style Sheet
  9. Type PayrollPreparation as the name of the file
  10. Click Add
  11. Create some styles as follows:
    body {
        background-color: white;
    }
    
    .bold          { font-weight: 600;   }
    .ng-model      { width:       90px;  }
    .work-contents { margin:      auto;
                     width:       625px; }
    .pay-contents  { margin:      auto;
                     width:       325px; }
    .font          { font-family: Georgia, 'Times New Roman', Times, serif; }
  12. In the Solution Explorer, right-click Scripts -> Add -> JavaScript File
  13. Type SalaryEvaluation as the name of the file
  14. Click Add
  15. Type the following code in the empty document:
    var appPayroll = angular.module("appPayroll", []);
    appPayroll.controller("PayrollController", calculate);
    
    function calculate($scope) {
        $scope.totalTime = function (a, b, c, d, e) {
            return Number(a || 0) + Number(b || 0) + Number(c || 0) + Number(d || 0) + Number(e || 0);
        }
    
        $scope.regularTime = function (a, b, c, d, e)
        {
            var total = Number(a || 0) + Number(b || 0) + Number(c || 0) + Number(d || 0) + Number(e || 0);
    
            if (total <= 40.00)
                return total;
            else
                return 40.00;
        }
    
        $scope.overtime = function (a, b, c, d, e) {
            var total = Number(a || 0) + Number(b || 0) + Number(c || 0) + Number(d || 0) + Number(e || 0);
    
            if (total <= 40.00)
                return 0.00;
            else
                return total - 40.00;
        }
    
        $scope.regularPay = function (a, b, c, d, e, f) {
            var regTime = $scope.regularTime(b, c, d, e, f);
    
            return Number(a || 0) * regTime;
        }
    
        $scope.overtimePay = function (a, b, c, d, e, f) {
            var over = $scope.overtime(b, c, d, e, f);
    
            return Number(a || 0) * over;
        }
    
        $scope.totalPay = function (x, y) {
            return x + y;
        }
    }
  16. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  17. Change the document as follows:
    using System.Web.Optimization;
    
    namespace PayrollPreparation3
    {
        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/SalaryEvaluation.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"));
            }
        }
    }
  18. In the Solution Explorer, expand Controllers and double-click HomeController.cs
  19. Create a method as follows:
    using System.Web.Mvc;
    
    namespace PayrollPreparation3.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 PayrollPreparation()
            {
                return View();
            }
        }
    }
  20. In the Solution Explorer, expand Home and expand Shared
  21. Double-click _Layout.cshtmnl to open the file
  22. 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", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Payroll Evaluation", "PayrollPreparation", "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>
  23. Click the HomeController.cs tab to access the controller
  24. In the class, right-click PayrollPreparation() -> Add -> View...
  25. Make sure the View Name text box displays PayrollPreparation. Click Add
  26. Change the document as follows:
    @{
        ViewBag.Title = "Payroll Preparation";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <div ng-app="appPayroll">
        <h2 class="font text-center bold">Payroll Preparation</h2>
    
        <hr />
    
        <form name="PayrollEvaluation" method="post" ng-controller="PayrollController">
            <div class="work-contents font">
                <table>
                    <tr>
                        <td class="bold">Hourly Salary:</td>
                        <td colspan="5"><input type="text" class="form-control ng-model" ng-model="hourlySalary" /></td>
                    </tr>
                </table>
                <table class="table table-striped">
                    <tr>
                        <td class="bold">&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="number" class="form-control ng-model" ng-model="Monday" /></td>
                        <td><input type="number" class="form-control ng-model" ng-model="Tuesday" /></td>
                        <td><input type="number" class="form-control ng-model" ng-model="Wednesday" /></td>
                        <td><input type="number" class="form-control ng-model" ng-model="Thursday" /></td>
                        <td><input type="number" class="form-control ng-model" ng-model="Friday" /></td>
                    </tr>
                </table>
            </div>
            <div class="pay-contents font">
                <table class="table table-striped">
                    <tr>
                        <td>&nbsp;</td>
                        <td class="text-center bold">Time</td>
                        <td class="text-center bold">Pay</td>
                    </tr>
                    <tr>
                        <td class="bold">Regular:</td>
                        <td class="text-center bold">{{regularTime(Monday, Tuesday, Wednesday, Thursday, Friday) | number : 2}}</td>
                        <td class="text-center bold">{{regularPay(hourlySalary, Monday, Tuesday, Wednesday, Thursday, Friday) | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Overtime:</td>
                        <td class="text-center bold">{{overtime(Monday, Tuesday, Wednesday, Thursday, Friday) | number : 2}}</td>
                        <td class="text-center bold">{{overtimePay(hourlySalary, Monday, Tuesday, Wednesday, Thursday, Friday) | number : 2}}</td>
                    </tr>
                    <tr>
                        <td class="bold">Total:</td>
                        <td class="text-center bold">{{totalTime(Monday, Tuesday, Wednesday, Thursday, Friday) | number : 2}}</td>
                        <td class="text-center bold">{{totalPay(regularPay(hourlySalary, Monday, Tuesday, Wednesday, Thursday, Friday), overtimePay(hourlySalary, Monday, Tuesday, Wednesday, Thursday, Friday)) | number : 2}}</td>
                    </tr>
                </table>
            </div>
        </form>
    </div>
  27. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Passing Arguments to a Scope

  28. Close the form and return to your programming environment
  29. In the text boxes, type the following values:
    Hourly Salary: 17.05:
    Monday:         8
    Tuesday:	    8.50
    Wednesday:     10
    Thursday:	    9.50
    Friday:	       10.50

    Passing Arguments to a Scope

    Passing Arguments to a Scope

    Passing Arguments to a Scope

  30. Close the browser and return to your programming environment

Scoping an Object

Introduction

As seen in our introduction to AngularJS controllers and objects, you can create an object in a controller. When it comes to a scope, you can attach an object to it and use that object in both your AngularJS code and the webpage.

Attaching an Object to a Scope

To create an object in a controller, use any of the available techniques except that you can attach it to a scope. As one way to start, you can attach a property to a $scope object and assign the curly brackets to it. Here is an example:

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

function create($scope) {
    $scope.waterMeter = {};
}

appCompany.controller("MeterController", create);

In the body of the object, add the members you want (properties and methods). Here is an example:

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

function addMeter($scope) {
    $scope.waterMeter = {
        meterNumber: "293-740",
        make: "Breston",
        model: "S-93749",
        size : "3/4 Inches" 
    };
}
appCompany.controller("MeterController", addMeter);

In the same way, you can create more objects by attaching them to a $scope object. Here are examples:

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

function addMeter($scope) {
    $scope.meterB293740 = {
        meterNumber: "293-740",
        make: "Breston",
        model: "S-93749",
        size : "3/4 Inches" 
    };
    $scope.meterVW820418 = {
        meterNumber: "820-418",
        make: "Vashty Worldwide",
        model: "DD-3840",
        size: "3/4 Inches"
    };
}
appCompany.controller("MeterController", addMeter);

If you need different types of objects, you can create different controllers and create the objects of each category in their respective controllers. Here is an example:

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

function addMeter($scope) {
    $scope.meterB293740 = {
        meterNumber: "293-740", make: "Breston",
        model: "S-93749", size : "3/4 Inches" 
    };
    $scope.meterVW820418 = {
        meterNumber: "820-418", make: "Vashty Worldwide",
        model: "DD-3840", size: "3/4 Inches"
    };
}
appCompany.controller("MeterController", addMeter);

function createCustomer($scope) {
    $scope.customer = {
        accountNumber : "2958-314-5294",
        meterNumber: "627-425",
        firstName: "Nicholas",
        lastName: "Thorn",
        address: "2599 Phenicia Road",
        city: "Silver Spring",
        county: "Montgomery",
        state: "MD" };
}
appCompany.controller("CustomerController", createCustomer);

As we saw in our introduction to objects in JavaScript, you can start an object with empty curly brackets. Outside the brackets, to create a property, type $scope., the name of the object, a period, and the desired name of the new property. You can then assign a value to it. Here are examples:

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

function addMeter($scope) {
    $scope.meterB293740 = {
        meterNumber: "293-740", make: "Breston",
        model: "S-93749", size : "3/4 Inches" 
    };
    $scope.meterVW820418 = {
        meterNumber: "820-418", make: "Vashty Worldwide",
        model: "DD-3840", size: "3/4 Inches"
    };
}
appCompany.controller("MeterController", addMeter);

function createCustomer($scope) {
    $scope.cust29583145294 = {
        accountNumber : "2958-314-5294",
        meterNumber: "627-425",
        firstName: "Nicholas",
        lastName: "Thorn",
        address: "2599 Phenicia Road",
        city: "Silver Spring",
        county: "Montgomery",
        state: "MD"
    };
    $scope.cust70293718594 = {};
    $scope.cust70293718594.accountNumber = "7029-371-8594";
    $scope.cust70293718594.meterNumber= "293-740";
    $scope.cust70293718594.firstName = "Danielle";
    $scope.cust70293718594.lastName = "Dormand";
    $scope.cust70293718594.address = "2515 Guthierez Street";
    $scope.cust70293718594.city = "Falls Church";
    $scope.cust70293718594.county = "";
    $scope.cust70293718594.state = "VA";
}
appCompany.controller("CustomerController", createCustomer);

Accessing an Object

To access the whole object in a webpage, simply use its name. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/WaterMeterManagement.js"></script>
<title>Water Distribution Company</title>
</head>
<body ng-app="appWaterCompany">
    <div ng-controller="MeterController">
        <p>Water Meter: {{waterMeter}}</p>
    </div>
</body>
</html>

To access a property, type the name of the object, a period, and the name of the property. Here are examples:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/WaterMeterManagement.js"></script>
<title>Water Distribution Company</title>
</head>
<body ng-app="appWaterCompany">
    <div ng-controller="MeterController">
        <p>Water Meter: {{meterB293740.make}} {{meterB293740.model}}</p>
    </div>

    <div ng-controller="CustomerController">
        <p>Customer: {{cust70293718594.firstName + " " + cust70293718594.lastName}}</p>
    </div>
</body>
</html>

Performing Operations on an Object

If you want to perform operations on an object, add a method to it. That is, attach a property to the object and assign an anonymous function to it. Here is an example:

$scope.cust70293718594 = {};
$scope.cust70293718594.accountNumber = "7029-371-8594";
$scope.cust70293718594.firstName = "Danielle";
$scope.cust70293718594.lastName = "Dormand";
$scope.cust70293718594.fullName = function () {
        return $scope.cust70293718594.firstName + " " + $scope.cust70293718594.lastName
};

To access the method in a webpage, apply the property to the object and use the parentheses.

Practical LearningPractical Learning: Ending the Lesson.


Previous Copyright © 2017-2022, FunctionX Next