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

November 16, 2015 / KB-0009

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

MVC with AngularJS

Part 1. Setting Up The Environment

1.1 Using Windows Explorer, copy the mvc.html file located in the C:\LabFiles directory over to the \labs\ directory.

2.1 Start the Web server if it is stopped.

Part 2. Understanding MVC Components

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

You should see the following content:

2.2 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.

2.3. 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.

2.4. Open the \labs\mvc.html file in your text editor.

You should see the following content:

    <!doctype html>
    <title>MVC with AngularJS</title>
    <script src="/js/angular.js"></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);

    <body ng-app="SimpleApp" ng-controller="TaxCalculator" style="font-family: monospace">
        Enter person's name: <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>


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

  • The model is presented by two JavaScript properties: person.name and person.income that are plugged into the framework by the ng-model attributes 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.
  • 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.
  • The up-to-date state of our model is echoed back to the user in the p element.
  • 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%).
  • The $scope parameter of the TaxCalculator constructor function is the context object passed in (or injected) by AngularJS. The $scope carries the model values updated in the View.
  • 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.

3.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:

    <br> The income tax rate (%): <input type="number" ng-model="tax.rate" min="0" max="100">

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 ...)

3.2. In the mvc.html file, locate the taxRate = 0.5; line and replace it with this content:

    var taxRate = $scope.tax.rate/100;

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 ...)

3.3. Save the file. Keep the file open in the text editor.

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

3.5. You should see the following updated page content:

3.6. 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.

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

Part 4. Review

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

Related Webinars

Related Training

AngularJS Training
AngularJS Programming
Instructor Led Virtual
AngularJS Training
Introduction to Responsive Web Development with AngularJS and Bootstrap
Instructor Led Virtual