KB-003 Core AngularJS Concepts

Core AngularJS Concepts

Check out these related webinars…

Introduction

In this article, we’re going to introduce a few of the core concepts of AngularJS. These concepts are critical to using AngularJS effectively and learning them will give you a good start to using AngularJS in your own development.

The article is targeted to people who have are new to AngularJS, but have some familiarity with JavaScript and web development. You should read this tutorial along with a practical tutorial like Getting Started with AngularJS.

Some Background on AngularJS

The AngularJS website answers “Why AngularJS” as follows:

HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

This power comes with a price – there are some radical differences between websites developed using AngularJS and any other web development you’ve probably done. Fundamentally, we have to move from describing pages in HTML markup, to creating an application that runs in JavaScript on the browser, and along the way, shows some information to the user using HTML markup. AngularJS uses the long-established Model-View-Controller, or MVC paradigm to make this display relatively easy.

Model-View-Controller

MVC is an application structure that was introduced in the 1970s by the Smalltalk programming language. Since then it’s been widely used in desktop GUIs and server-side web frameworks. Angular translates MVC to the browser.

The basic premise of MVC is that we’d like to work with data in memory in a way that’s natural to the programming language, and then separately define how that data is shown to the user. In AngularJS, the data, or “model” is contained in plain javascript variables in a “scope” that AngularJS manages for us. The “view” is represented as a template which is made up of HTML markup, along with substitutions that will be replaced with model data from the scope.

In addition to seeing a representation of data, a user generally wants to change that data. In MVC, we link the user interface to code that interprets the user’s wishes and updates the data, which is then rendered back out to the user through the view. In AngularJS, this javascript code is contained in a “controller” object that is also managed by AngularJS.

What You See is Not What You Get!

Normally, when a browser loads an HTML page, it runs the HTML through a parser to generate an internal “Document Object Model”, or DOM, that represents our desired view of the page. Then the browser runs through the DOM and creates the operating-system-level user interface components that get drawn on the screen, based on the DOM.

AngularJS changes this process. Under AngularJS, the HTML that forms the page is treated as input to the AngularJS view system. AngularJS reads the input DOM, hides it away, and generates another DOM that is actually output by the browser. So what you see on the browser’s screen is not actually a rendering of the HTML that is in the source file, but a rendering of the DOM that AngularJS generated, based on the input DOM and the value of any model variables.

Developers who are used to using a library like jQuery to manipulate the DOM often find this translation a little strange. They often ask how to manipulate the DOM in AngularJS. The answer is “you don’t”. You simply put data into the the model (or “scope”) and let AngularJS create the output DOM for you, based on the templates contained in the input DOM.

Directives

While it’s reading the input DOM, AngularJS looks for “directives” in the DOM. When it finds a directive, it executes the JavaScript code that implements the directive (we’re simplifying a bit here!), and then it may (depending on the directive code) replace the directive with the output of a “template” that is associated with the directive.

Directives can be either attributes on HTML elements, or they can be elements in the DOM itself.

<input type=text width=40 ng-model=aVariable>
<mydirective-table></mydirective-table>

In the case of elements, the element is not really an HTML element, but we can use it as though it were an element. AngularJS will replace it with the template output. This is how we “extend HTML” with AngularJS.

Templates

When AngularJS creates its output DOM, it looks in the input DOM for specially-formatted “templates” or “expressions” and replaces them with the evaluated form of the expression.

<!doctype html>
<html ng-app>
<head>
<meta charset="UTF-8" />
    <title>Hello AngularJS!</title>
    <script src='/js/angular.js'></script>
</head>
<body style='font-family: monospace'>
    Enter user name: <input type="text" ng-model='name'><br>
    Enter user age : <input type="number" ng-model='age' min='1' max='121'>
    <p ng-show='name' style='color:blue;'>User {{name}} is {{age}} years old</p>
</body>
</html>

In the example above, the expression “{{name}}” will be replaced with the value of the ‘name’ variable in the application scope. Also, since the input box calls out ‘ng-model=”name”‘, the user’s input will be placed into the same variable in the application scope.

Controllers and Scopes

Controllers are where we put code that the user interface components will call when the user does something. One thing that often confuses people is that the way of defining a controller is a little strange – we provide a constructor function for a javascript object. We don’t just define functions in the global space, as you may be used to with other Javascript frameworks.

You see, AngularJS uses an Inversion of Control paradigm, along with dependency injection. So, what it really wants is for you to tell it how to create the controller and define its methods. Then, AngularJS will create the controller on its own at such time as its needed by the user interface.

Consider the following example:

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);
    };
   });

Notice that we’re not defining any functions in the global space here. All we’re doing is providing AngularJS with a function that it can call, if and when it needs to create an instance of a “TaxCalculator” controller. This function is handed a reference to the current scope, and it creates functions and sets up data in that scope. When the component events are attached to the controller using directives like”, the directives have access to these functions that are defined using the controller setup function.

Conclusion

Traditionally, JavaScript usage in web pages has been pretty much limited to very small functions used for handling events, or doing client-side validation. However, AngularJS takes us from describing page layouts to creating applications that run in JavaScript. As a result, even experienced web developers need to revisit some key concepts in application design and the JavaScript language. It’s important to remember that AngularJS takes a different approach to displaying the user interface. It implements a full inversion of control environment linked to dynamic template processing. The AngularJS paradigm borrows from MVC development in languages like Smalltalk. It can be a radical departure from traditional web page design. But with a few key concepts in hand, you’ll find AngularJS to be a powerful addition to your development toolbox.

Related Webinars

Related Training

WA2425
AngularJS Training

AngularJS Programming

Montreal 

Toronto 

Calgary 

Ottawa 

Toronto 

WA2406
AngularJS Training

Introduction to Responsive Web Development with AngularJS and Bootstrap

Calgary 

Vancouver 

Montreal