An introduction to AngularJS

If you wanna talk about AngularJS you’ve to explain the concept of: Directive, Controller, Expressions, Two way Data Biding and Modules.

AngularJS is a javascript framework maintaned by Google who helps developer to build awesome Single Page App. It is born especially to build web app after a user has logged in, so for all the apps that doesn’t need to be indexed by search engines likes CRM, ERP, Social Network and so on. You can compare angular as a new HTML compiler which allows you to create your own domain specific language in HTML, by attaching your own behavior to any HTML element, attribute or text. In AngularJS the term “compile the HTML” means attaching event listeners to the HTML to make it interactive. It follows a declarative approach in order to infer behaviour on your html page.

The basic idea of AngularJS is to extend the HTML markup with special attributes called Directives in order to trigger Javascript function. AngularJS has Controllers to add logic and behaviour in a web app. They are important because each controller has a $scope, an easy way to link model to view. An AngularJS web app is organized in modules, so it’s easily maintanable, testable and readable. Furthermore with modules you can define app dependencies (following the design pattern called Law of Demeter as Angular’s dependency injection system).

What happens when an angular webapp is loaded into the browser?

Let’s see an Angular Application Flow

  1. First, a client browser makes an HTTP request to the server. Once the server sent the response to the browser, it loads the requested HTML page as template
  2. Seconds, Angular waits for the page to be fully loaded, then it scans the DOM and looks for directives and data-bindings.
  3. Angular compiles the template, adds listeners on DOM elements and evaluates bindings.

Let’s start from Directives

Directives are a mechanism through which the HTML is extended and enhanced. In AngularJS they’re is a bunch of directives.

A directive is a marker on a HTML tag that tells Angular to run or reference some Javascript code.

Let’s see a few kinds of Directives:

  1. ng-app – attach the application module on the page – it tells to Angular which parts of the page it should manage.
    <html ng-app="store">	
    
  2. ng-controller – attach a Controller function to the page
    <body ng-controller="StoreController as store">
    
  3. ng-show / ng-hide – display a section based on an Expression
    <h1 ng-show="name">Hello, {{name}}!</h1>	 	 
    <div class="gallery" ng-show="product.images.length">	 	 
    
  4. ng-repeat – repeat a section for each item in an Array
    <li ng-repeat="product in store. products">{{product.name}}</li>
    
  5. ng-src show an image
    <img ng-src="{{product.images[0]}}">
    
  6. ng-init evaluate an expression in the current scope
    <section ng-init="tab = 1">
    
  7. ng-click allows to specify custom behavior when an element is clicked.
    <a href ng-click="tab = 1">Description</a>
    
  8. ng-model: binds the form element value to a property
  9. ng-submit: allows to call a function when a form is submitted
    					<form name="reviewForm" ng-controller="ReviewController as reviewCtrl" ng-submit="reviewCtrl.addReview(product)">
    
    
  10. ng-include – it fetches, compiles and includes an external HTML fragment: usefull for eliminating the duplication of the code
    <ul class="list-group">
    <li class="list-group-item" ng-repeat="product in store.products">
    
    <h3 ng-include="'product-title.html'"></h3>
    <section ng-controller="PanelController as panel">
    
    <!-- product-title.html -->
    {{product.name}}
    <em class="pull-right">${{product.price}}</em>
    

What about Controllers and $scope?

In Angular, you manage areas of the page with JavaScript classes called controllers.

The $scope is the glue between the controller and the view. A scope is the context in which application data are stored and the expression are evaluated. Each controller has its own scope. The scope is our view model and it’s the glue between the view and the controller.

Controller are associated to a DOM element trought a ng-controller directive.

First example: Listing quiz on a page

In the example hereafter we display a list of quiz in a view. For this purpose we have defined a new controller called QuizListController. In it’s scope a new array of quizzes objects called quizList was created. Each quiz object has two fields: title and description. The controller is linked to the div thanks to the directive ng-controller. Trought the directive ng-repeat AngularJS scans the quizList array and for each element generates a new table row with two cells: one for the quiz’s title and the other for the quix’s description.

  <body ng-app>
    
	<h1>Quiz List</h1>
    <div ng-controller="QuizListController">  
      <table class="table table-hover">
        <thead>
          <tr>
            <th>Quiz Title</th>
            <th>Quiz Description</th>
			<th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="quiz in quizList">
            <td>{{quiz.title}}</td>
            <td>{{quiz.description}}</td>
			<td>
			  <button type="button" class="btn btn-default">
                  <span class="glyphicon glyphicon-info-sign"></span>
              </button>
              <button type="button" class="btn btn-default edit">
                  <span class="glyphicon glyphicon-pencil"></span>
              </button>
              <button type="button" class="btn btn-default">
                  <span class="glyphicon glyphicon-remove"></span>
              </button>

              <button type="button" class="btn btn-primary" data-action="add-questions">
                  Add Questions
              </button>
			
			</td>
          </tr>
		</tbody>
      </table>
	</div>
  
  <script type="text/javascript">
    function QuizListController($scope) {
      $scope.quizList = [
        {
          title: "Data Mining Quiz",
          description: "Data mining online test description..."
        }
        ,
        {
          title: "Digital Marketing Quiz",
          description: "Digital marketing online test description..."
        },
		{
		  title: "Artificial Intelligence Quiz",
          description: "Artificial Intelligence online test description..."
		}
      ];
    }
    
  </script>
  
  </body>


This is how the page layout will be rendered:
Listing quiz with an angularjs app

You can download the complete source code of this example here.

Filters

A filter formats the value of an expression for display to the user.

See more about filter on the official documentation website.

General schema:

 {{ data* | filter: options* }}

orderBy

Let’s say we want the quiz list ordered by title. So the first element will be Artificial Intelligence Quiz, the second one will be Data Mining Quiz and so on. We have to use the orderBy filter that uses the title property to sort the objects before iterating through them.

 <tr ng-repeat="quiz in quizList | orderBy: 'title'">
            <td>{{quiz.title}}</td>
            <td>{{quiz.description}}</td>

uppercase / lowecase

If we want the title in capital letters, we have to use the uppercase filter.

 <tr ng-repeat="quiz in quizList | orderBy: 'title'">
            <td>{{quiz.title | uppercase}}</td>

limitTo

With the filter limitTo we can limit the length of a string.
For instance if we want to display only the first twenty chars of the description:

<td>{{quiz.description| limitTo: 20}}</td>

date

If you want to display the current date on a page, you need to assign the Date object to scope where you want to evaluate this expression.

<div ng-controller="QuizListController">  
	  <p>Today is {{today | date: 'MM/dd/yyyy @ h:mma'}}</p>

and in the controller:

 function QuizListController($scope) {
	  $scope.today = new Date();

You can also create custom filters: http://jsfiddle.net/tUyyx/

Two ways Data Binding

Data-Binding is a key concept of this MVVM framework. AngularJS uses a style of programming called Data-Binding in order to automatically synchronize the data between the model and view components.
Two-way data binding means Expressions are re-evaluated when a property changes.

In order to implement a data-biding you have to use:

  • {{ … }} double-curly notation for data binding
  • ng-model, which binds an input to part of the model
<body ng-app>
<strong>Course Name:</strong> {{courseName}}<br />
<label>You are writing: <input type="text" ng-model="courseName"/></label><br />
</body>


Custom Directives

Directives allow you to improve the expressivity of your HTML. With custom directive you can create new html tag, attributes or comment that define the behavior of your application.

AngularJS offers specific API for registering directives inside a module.

Let’s see how to create custom directives:

  1. First method: creating a custom tag element called <product-title></product-title>

    The dash in HTML translate to camelCase in Javascript

    app.directive('productTitle', function() {
    	return {
    		restrict: 'E', // (type of directive, E for element),
    		templateUrl: 'product-title.html'
    	};
    });
    
    
    
  2. Second method: creating a custom attribute of an element called product-title:
    <h3 product-title></h3>
    app.directive('productTitle', function() {
    	return {
    		restrict: 'A', // (type of directive, A for attribute),
    		templateUrl: 'product-title.html'
    	};
    });
    
    

Online Course

Leave a Reply