• US Inquiries / 1 877 517 6540
  • Canadian Inquiries / 1 866 206 4644
submit to reddit

Sept 14, 2015 / KB-006

MVC With AngularJS

Check out these related webinars...

Unit Testing AngularJS Code
Get Ready for Angular 2.0
Introduction to AngularUI and UI-Bootstrap
Building AngularJS Apps with Grunt.js
Hybrid Mobile Development with AngularJS and Ionic
JavaScript for Web 2.0 Development
AngularJS

MVC with AngularJS

In this lab, you will learn about the Model-View-Controller (MVC) pattern as it is implemented by AngularJS.

Part 1 - Setting Up The Environment

  1. Copy the mvc.html file over to the C:\Software\nginx\html\labs\ directory.
  2. Open the Command Prompt window and unless you are already in the C:\Software\nginx directory, type in the following command at the prompt and press ENTER:

    cd C:\Software\nginx

  3. Start the nginx web server by executing the following command:

    start nginx

This command will launch the nginx web server that starts listening on port 80 ready to service your browser requests.

Keep the Command Prompt window open.

Part 2 - Understanding MVC Components

  1. Open Google Chrome browser and navigate to http://localhost/labs/mvc.html

You should see the following content:

  1. Enter Bill Smith in the Enter person's name input box and 30000 for the person's income and click the Apply Tax button.

You will be presented with the following screen with a pop up message dialog:

As you can see, Bill Smith just lost 50% of his disposable income.

  1. Click OK in the pop-up message dialog.

Let's take a look at how AngularJS (not the Revenue Service, of course!) did that to Bill Smith.

  1. Open the C:\Software\nginx\html\labs\mvc.html file in your text editor.

You should see the following content:

<!doctype html>
<html>
<head>
<title>MVC with AngularJS</title>
<script src="/js/angular.js"></script>

<script>

angular.module("SimpleApp", [])
   // Controller
   .controller("TaxCalculator", function($scope) {
      //Initialize model data
      $scope.person = {
         name: "",
         income: 0
      };

      // Operation (behavior)
      $scope.applyTax = function() {
         var person = $scope.person.name;
         var income = $scope.person.income;
         var taxRate = 0.5;
         var tax = income * taxRate;

         alert("Grab $ " + tax + " in taxes from poor soul " + person);
      };
   });
</script>
</head>

<body ng-app="SimpleApp" ng-controller="TaxCalculator" style="font-family: monospace">
    Enter person's name&nbsp;&nbsp;: <input type="text" ng-model="person.name">
    <br> Enter person's income: <input type="number" ng-model="person.income">
    <p style="color: blue;">The income of [{{person.name}}] is $[{{person.income}}]</p>
    <button ng-click="applyTax()">Apply Tax</button>
</body>

</html>

Let's review the elements of the MVC pattern on the page.

  1. The model is presented by two JavaScript properties: person.name and person.income that are plugged into the framework by theng-modelattributes of the input HTML elements. For the person.income numeric value we use the number input element of HTML5 that helps with input filtering (any user input other than a number will be discarded). Note that we are using the dot '.' notation to group properties (name and income) into a single "namespace" called person. This idiom helps build object.property hierarchies.

  2. The UI (View) of the page is represented by the DOM (the input HTML elements); the UI elements are mapped to the _person.name_and _person.income_JavaScript properties.

  3. The up-to-date state of our model is echoed back to the user in the p element.

  4. We are creating a controller called TaxCalculator. It will be the controller part of the MVC structure on our page. The controller contains the business logic of calculating and applying the tax (of the whopping 50%).

  5. The $scope parameter of the TaxCalculator constructorfunction is the context object passed in (or injected) by AngularJS. The $scope carries the model values updated in the View.

  6. The applyTax function represents the operation attached to our controller and it's bound to the UI by way of the ng-click directive of the Apply Tax button.

So, in essence, the MVC pattern is implemented in our AngularJS-driven page as follows: the View is the Document Object Model (DOM), the Controller is a JavaScript class, and the Model is the data stored in JavaScript variables or object properties.

Keep the file open in the text editor as we are going to make changes to our AngularJS MVC application.

Part 3 - Working with the MVC Components

Currently, our MVC application has the tax rate hard-coded and set to 50% (taxRate = 0.5;). Let's improve on this and make our application more flexible by exposing the tax rate to the user through the UI.

  1. In your text editor that holds the mvc.html file, locate the
    Enter person's income: <input type="number" . . .
    line and right below it enter the following statement in one line:


    The income tax rate (%):

As a result, you should have the following updated content in this part of our web page:

(content skipped for space ...)

<br> Enter person's income: <input type="number" ng-model="person.income">
<br> The income tax rate (%): <input type="number" ng-model="tax.rate" min="0" max="100">
<p style="color: blue;">The income of [{{person.name}}] is $[{{person.income}}]</p>

(content skipped for space ...)
  1. In the mvc.html file, locate the taxRate = 0.5; line and replace it with this content:

    var taxRate = $scope.tax.rate/100;</pre>
    

As a result, you should have the following updated content in this part of our web page:

(content skipped for space ...)

$scope.applyTax = function() {
   var person = $scope.person.name;
   var income = $scope.person.income;
   var taxRate = $scope.tax.rate/100;
   var tax = income * taxRate;

(content skipped for space ...)
  1. Save the file. Keep the file open in the text editor.

  2. Switch to Chrome and refresh the browser view by pressing Ctrl-R.

  3. You should see the following updated page content:

Now you have the income tax rate control that adds flexibility to our application. Try out applying different income tax rates (the supported rates are 0% through 100%).

Note: If you have a problem applying taxes (you don't see a pop up dialog stating how much tax was grabbed (withheld) from the taxpayer), press Ctrl-Shift-J in Chrome to open the JavaScript console and see the exception (error) that prevented the controller's applyTax operation from completing. You may see an error similar to this one:

This error is the result of you entering the rate value that is in conflict with the defined number input range (input is beyond the [0 - 100] range, e.g. a negative value).

You can click at any of the links in the console output to drill down and inspect what is happening under the hood. In our labs, we use angular.js at source level (not minimized for production) so you can get some insights into the workings of this framework.

To hide the JavaScript console in Chrome press Ctrl-Shift-J again.

Part 4 - Cleaning Up

  1. Close Chrome browser.

  2. In the Command Prompt window where you started the nginx web server, enter in the following command:

    nginx -s stop

This command will stop the web server.

You can keep the Command Prompt window open.

This is the last step in this lab.

Part 5 - Review

In this lab, you learned about the Model-View-Controller (MVC) pattern as it is implemented by AngularJS.

Related Webinars

Related Training

WA2425
AngularJS Training
AngularJS Programming
Montreal
Instructor Led Virtual
Toronto
WA2406
AngularJS Training
Introduction to Responsive Web Development with AngularJS and Bootstrap
Vancouver
Instructor Led Virtual
Calgary