Fundamentals of Controllers

Introduction

In AngularJS, a controller is an object used to solve a problem.

Practical LearningPractical Learning: Introducing AngularJS Controllers

  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 CableCompany2
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, click the MVC icon
  6. Click OK
  7. To create a new CSS file, in the Solution Explorer, right-click Content -> Add -> New Item...
  8. In the left frame of the Add New Item dialog box, click Web and click Markup under it. In the middle frame, click Style Sheet
  9. Change the file Name to CableCompany
  10. Click Add
  11. Change the document as follows:
    body {
        background-color: white;
    }
    
    form                        { padding: 1em;
                                  margin:           auto;
                                  width:            550px;
                                  background-color: #e0d4c0;
                                  border:           1px solid maroon; }
    form div                    { padding:          4px;
                                  margin:           0 0 1px 0; }
    input[type=number]          { width:            80px;
                                  float:            right;
                                  border:           1px solid maroon; }
    input[type=number]:focus    { outline:          1px solid #ff6a00; }
    input[type=button]          { border:           0;
                                  border-radius:    10px;
                                  font-size:        14px;
                                  width:            130px;
                                  margin-left:      100px;
                                  background-color: brown;
                                  padding:          0.75em;
                                  color:            yellow; }
    input[type=button]:hover    { color:            white;
                                  cursor:           pointer;
                                  background-color: chocolate; }
    form > fieldset > div > div { margin:           0 0 5px 0; }
    .bold                       { font-weight:      600;       }
    .main-title                 { font-family:      'Times New Roman', Garamond, Georgia, serif;
                                  color:            maroon; }
    .caption                    { width:            11.45em;
                                  display:          table-cell; }
    .resulting-value            { width:            6em;
                                  background-color: white;
                                  display:          table-cell;
                                  border:           1px solid maroon; }
  12. In the Solution Explorer, right-click CableCompany2 and click Manage NuGet Packages...
  13. Click the Browser button.
    Do a search on angularjs (you must be connected to the Internet)
  14. In the list, click angularjs:

    Microsoft Visual Studio - AngularJS Installation

  15. In the middle-right frame, click Install. If a dialog box comes up, read it and click OK:

    Preview

  16. In the Solution Explorer, right-click Scripts -> Add -> New Item...
  17. In the left frame of the Add New Item dialog box, click Web and, in the middle frame, click JavaScript File
  18. Change the Name of the file to BillPreparation
  19. Click Add
  20. Change the document as follows:
    var appCableCompany = angular.module('appCableCompany', []);
  21. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  22. Change the document as follows:
    using System.Web;
    using System.Web.Optimization;
    
    namespace CableCompany2
    {
        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/BillPreparation.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/CableCompany.css"));
            }
        }
    }
  23. In the Solution Explorer, click the button on the left of Views to expand it. In the same way, expand the Shared folder
  24. Under Shared, double-click _Layout.cshtml to open it
  25. 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>ESCAPE - Bill Evaluation :: @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("ESCAPE", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Bill Evaluation", "BillEvaluation", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p class="text-center">&copy; @DateTime.Now.Year - ESCAPE (Eastern Shore Company and Production Entertainment)</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  26. In the Solution Explorer, click the button on the left of Controllers to expand it
  27. Under Controllers, double-click HomeController.cs to open it
  28. Add a method named BillEvaluation as follows:
    using System.Web.Mvc;
    
    namespace CableCompany3.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult BillEvaluation()
            {
                return View();
            }
        }
    }
  29. In the class, right-click inside the BillEvaluation() method and click Add View...
  30. In the dialog box, make sure the text box displays BillEvaluation and click Add
  31. Change the document as follows:
    @{
        ViewBag.Title = "Bill Evaluation";
    }
    
    <h1 class="text-center main-title bold">Eastern Shore Company and Production Entertainment</h1>
    <h2 class="text-center main-title bold">Bill Evaluation</h2>
    
    <form name="BillEvaluation" method="post" ng-app="appCableCompany">
        <fieldset>
            <legend>Cable TV Services</legend>
    
            <div class="row">
                <div class="col-md-6">
                    <div>
                        <label for="CableTVBasicFee">Cable TV Basic Fee:</label>
                        <input type="number" id="CableTVBasicFee" ng-model="CableTVBasicFee" />
                    </div>
                    <div>
                        <label for="DVRService">DVR Service:</label>
                        <input type="number" id="DVRService" ng-model="DVRService" />
                    </div>
                    <div>
                        <label for="SportsPackage">Sports Package:</label>
                        <input type="number" id="SportsPackage" ng-model="SportsPackage" />
                    </div>
                    <div>
                        <span class="caption bold">Sub-Total:</span>
                        <span class="resulting-value">{{(CableTVBasicFee + DVRService + SportsPackage).toFixed(2)}}</span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div>
                        <span class="caption bold">FCC Fee:</span>
                        <span class="resulting-value">{{((CableTVBasicFee + DVRService + SportsPackage) * 0.00250881).toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">County Taxes:</span>
                        <span class="resulting-value">{{((CableTVBasicFee + DVRService + SportsPackage + fccFee) * 0.0072668) | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">State Taxes:</span>
                        <span class="resulting-value">{{((CableTVBasicFee + DVRService + SportsPackage + fccFee) * 0.0042493) | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Payment Amount:</span>
                        <span class="resulting-value">{{(CableTVBasicFee + DVRService + SportsPackage + fccFee + ((CableTVBasicFee + DVRService + SportsPackage + fccFee) * 0.0072668) + ((CableTVBasicFee + DVRService + SportsPackage + fccFee) * 0.0042493)) | number:2}}</span>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>

Introduction to Creating an AngularJS Controller

To create a controller in AngularJS, you can use the following formula:

module.controller('controller-name', options)

You can start with the name of the module variable, followed by .controller(), and some options in the parentheses. Here is an example:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script>
    var appModule = angular.module('customized', []);
    appModule.controller('EmployeesController', options);
</script>

Practical LearningPractical Learning: Creating a Controller

Fundamentals of Components

Introduction

In general computer use, a component is anything that contributes to the functionality of a computer program. It can be a button on a toolbar, a photo in a webpage, a check box in a form, etc. A component can even be as large as a calculator (as a descktop application). Even a view (a webpage) is just a component. As you may imagine, this means that a component can contain one or more other components, or one component can belong to another component, or one component can depend on another component (like a check box or a button depends on a webpage), or one component can depend on a component that itself depends on another component, etc.

In the same way, in AngularJS, a component is an object that solves one or more problems. To let you perform various types of operations on a webpage or a website, AngularJS provides various types of components. One of the types of components that AngularJS supports is a controller.

There are two categories of components you will use. Built-in components are those that have already been created and you can use them directly in your code. Custom components are those you will create, such as controllers.

Creating a Component

To let you create a component, AngularJS provides a function for each type. Most of those functions use the following syntax:

function-name(component-name, options)

At the right time, you will know the name of the function to use and what the function is used for. For example, to let you create a controller, AngularJS provides a function named controller. Its syntax is:

controller('controller-name', options)

The functions of all or most components take two arguments. That's also the case for a controller.

When creating a component, you must give it a name. This is the role of the first argument. The name is provided as a string. Except for controllers, the names of most components follow the camelCase. That is, if the name is in one word, it should (must) be in lowercase. If the name is made of various words, the first word must be in lowercase; the first letter of each subsequent word must then be in uppercase while the other letters are in lowercase.

The name of a controller follows a slight exception, which is not a rule but a suggestion. The name of a controller follows the CamelCase. That is, if the name is in one word, the first letter is in uppercase while the other letters are in lowercase. If the name is made of various words, each word starts with an uppercase letter while the other letters are in lowercase. As another suggestion used in ASP.NET MVC, if you want, end the name of a controller with Controller (unlike ASP.NET MVC, in AngularJS, this is not a rule but a suggestion).

Registering a Component

To actually get the component to work in your code, you must register it. You have various options. If you had declared a variable for a module, to register a component, type the name of the module variable, a period, and the creation of the module. Here is an example:

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

<script>
    var appModule = angular.module('customized', []);
    appModule.controller('EmployeesController', options);
</script>

Another technique to register a component is to create it immediately after the creation of another component. In this case, after the creation of another controller, type a period and create the component. Here is an example:

<script type="text/javascript">
    var appExercise = angular.module('business', []).controller('LoansController',  options);
</script>

This is also referred to as attaching one component to another.

In the above case, you don't need a variable for the module. Here is an example:

<script type="text/javascript">
    angular.module('business', []).controller('SeasonWorkController', options);
</script>

You can also start the creation of the component on its own line, like this:

<script type="text/javascript">
    angular.module('business', []).
    controller('TimeSheetsController', options);
</script>

or like this:

<script type="text/javascript">
    angular.module('business', [])
    .controller('ProgramEvaluationController', options);
</script>

In the same way, you can attach the creation of a component to another and to another, and so on. Here is an example:

<script type="text/javascript">
    angular.module('business', []).controller('CustomersController', options1).controller('EmployeesController', options2).controller('ProductsDistributtionController', options3);
</script>

This is the same as:

<script type="text/javascript">
    angular.module('business', []).
    controller('CustomersController', options1).
    controller('EmployeesController', options2).
    controller('ProductsDistributtionController', options3);
</script>

And is the same as:

<script type="text/javascript">
    angular.module('business', [])
    .controller('CustomersController', options1)
    .controller('EmployeesController', options2)
    .controller('ProductsDistributtionController', options3);
</script>

You can also create the same module, as long as you use the same module name, and attach a different component creation to each. Here are examples:

<script type="text/javascript">
    angular.module('business', []).controller('TimeSheetsController', options1);
    angular.module('business', []).controller('SubscriptionController', options2);
    angular.module('business', []).controller('ProgramEvaluationController', options3);
</script>

The Options of a Component

The second argument of a component specifies the role of the component with some options.

A Local Component

As seen for modules, you can create a component in the webpage where it will be used. This is referred to as a local component. That's the case for all controllers in our previous examples.

An External Controller

You can use the same above techniques to create a controller in an external file. You can create the controller in the same file where you are creating the module. Here is an example:

var appModule = angular.module('toysModule', []);
appModule.controller('ToysController', something);

As an alternative, you can create the module in its own file, and then create a controller in its own file.

After creating a controller in an external file, you must create a link to that file in any document where you want to use the controller. If you had created the module and the controller in different files, you must link both. The linking is done the same way as for a JavaScript file.

Using a Controller

After creating a controller, you should indicate where it would be used. As done for a module, you can use or create an HTML tag, such as a <DIV> or a form tag. The tag you decide to use can be nested in the tag used by the module. To support this, AngularJS provides a directive named ng-controller. To apply it, add it as an attribute to the desired tag and assign the name of the controller to it. Here is an example:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<div ng-app="customized">
    <div ng-controller="EmployeesController">

    </div>
</div>

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

If the tag that has the module attribute doesn't have nested tags that must individually use controllers, you can add the controller attribute to the tag that also uses the module. Here is an example:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<div ng-app="customized" ng-controller="EmployeesController">

</div>

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

Practical LearningPractical Learning: Introducing AngularJS Controllers

  1. Click the BillEvaluation.cshtml tab to access its document and change it as follows:
    @{
        ViewBag.Title = "Bill Evaluation";
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <h1 class="text-center main-title bold">Eastern Shore Company and Production Entertainment</h1>
    <h2 class="text-center main-title bold">Bill Evaluation</h2>
    
    <form name="BillEvaluation" method="post" ng-app="appCableCompany">
        <fieldset ng-controller="BillsController">
            <legend>Cable TV Services</legend>
    
            <div class="row">
                
             . . . No Change
    
            </div>
        </fieldset>
    </form>
    
    ng-controller="BillsController">
            <legend>Cable TV Services</legend>
    
            . . . No Change
        </fieldset>
    </form>
  2. To save everything, on the Standard toolbar, click the Save All button
  3. Close your programming environment

Previous Copyright © 2017-2019, FunctionX Next