AngularJS - MVC Architecture

Majority of javascript developers use AngularJs MVC pattern, because its offers architectural benefits over standard javascript. It decouples the model and view which leads to effortless maintenance in the project.


Model

Model represents the current state of the application data. Model is primarily concerned with business data. Model consistently notifies its observers (e.g views) that a change has occurred so that views reacts accordingly.

For Example: Lets consider there is a model that holds the value for a dropdown list on the page. Once the model is updated it notifies the dropdown to show the new set of values.

View

View is a visual representation of current state of the model. A view consistently observes the model and once the model notifies a change, it reacts accordingly. View is a DOM element which interacts with the users.

Controller

In Angular, controller is a Javascript function which controls the models and views. Controller has two parts i.e state ($scope variable) and behavior ($scope function). Controller is attached to the DOM via the ng-controller directive.

Controller runs only once during the page load. After that a hook is created between View (DOM) and Model ($scope variable/ $scope function). Once the view is updated all the hooked functions for the respective controller are executed. A page can have more than one controller. It can be associated to any DOM element like div,p,input,label.

Sample code for above output

<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<body ng-app="employeeApp"> 
 <div ng-controller="pfController">
  Please Enter Your Basic Pay : <input ng-model="basicAmount" type="text"/>
  <p ng-bind="pf"></p>
  <p ng-bind="epf"></p>
  <p class="ng-cloak">{{ pfAmount() }}</p>
 </div>
</body>
<script>
var employeeApp = angular.module("employeeApp",[]);
 employeeApp.controller("pfController",function($scope){ 
 /* scope varibales */
 $scope.basicAmount = 0;$scope.pf='';$scope.epf='';
 
 /* scope function - Below function will call when 
 you trying to change the value in basic Pay textbox */
 
 $scope.pfAmount = function(){
  $scope.pf  = "PF Amount for Your Basic Pay  : "+($scope.basicAmount*12)/100;
  $scope.epf = "EPF Amount for Your Basic Pay : "+($scope.basicAmount*12)/100;
  return "Above Calculation is 12% of Basic Pay";
 };
});
</script>

Previous Topic : AngularJS Basics Directives

An Introduction to the AngularJS Basics Directives Part1

Angularjs directive list

ngApp

The first ngApp found in the document is used to define the root element to auto-bootstrap an application. ngapp is typically placed near the root element of the page like in the body or html tag. ng-app executes at priority level 0.

ngInit

This directive is used to initialize the application data. ng-init executes at priority level 450.

ngRepeat

This directive is used to iterate over the properties of an object. ng-repeat executes at priority level 1000.

ngCloak

Generally ngcloak directives is used to avoid the flickering effect caused by the html template display. All html elements (including their children) that are tagged with the ngCloak directive are hidden because ng-cloak have css rule embedded within angular.js and angular.min.js.When Angular encounters this directive during the compilation of the template it deletes the ngCloak css attribute, making the compiled element visible. ng-cloak executes at priority level 0.

Example for ngApp,ngInit,ngRepeat,ngCloak

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<div ng-app="initrepeatApp" ng-init="list = [1,2,3,4,5]">
<p>Iterate the list object </p>
<ul>
 <li ng-repeat="val in list">
  <span ng-cloak>{{val}}</span>
 </li>
</ul>
</div>
<script>
var initrepeatApp = angular.module("initrepeatApp",[]);
</script>

ngModel

ngModel binds the view to the model. View can be any HTML controls (input, select, textarea). Model can be any application data. Keeps the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). ng-model executes at priority level 1.

ngController

Controller is attached to the DOM via the ng-controller directive. Controllers are used to set up the initial state of the $scope object or add method or behavior to the $scope object. This directive creates new scope object for each controller. ng-repeat executes at priority level 500.

ngBind

The ngbind attribute will continuously update the content of the specified HTML element with the value of a given expression. ngbind directive is preferable than double curly markup because double curly markup is displayed by the browser in its raw state before angularjs complies it.So user can see flickering while the page is loading.Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading. ng-bind executes at priority level 0.

Example for ngModel,ngController,ngBind

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<body ng-app="employeeApp"> 
 <div ng-controller="pfController">
  Please Enter Your Basic Pay : <input ng-model="basicAmount" type="text">
  <p ng-bind="pfAmount()"></p>
 </div>
</body>
<script>
 var employeeApp = angular.module("employeeApp",[]);
  employeeApp.controller("pfController",function($scope){
   $scope.basicAmount = 0;
   $scope.pfAmount = function(){   
 return "PF Amount for Your Basic Pay : "+($scope.basicAmount*12)/100;
   };
 });    
</script>
Previous Topic : Two way data binding
Next Topic : Angularjs MVC Pattern

Two way data binding vs Traditional Approach in AngularJS with example

Two-way data-binding

Two way data binding means automatic synchronization of data between the model and view components. Whenever the model changes,angular will cause the view to automatically update leading to no explicit DOM (Document Object Model) manipulation and vice versa.

Two Way Data Binding AngularJS

Two way binding example in AngularJS

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<div ng-app="">
Name: <input type="text" ng-model="name">
<p ng-bind="name"></p>
</div>

Explanation

The above code when a model(ng-model) variable is bound to a HTML element(input tag) that can both change and display the value of the variable.By using ng-bind to display the model.

Traditional Approach

In traditional approach we need to read user input and merge with the template to display the view on the screen. Everything we need to do explicitly.

One way data binding angularjs

Example in Jquery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("#name").keypress(function(){
        $("#textboxvalue").text($("#name").val());
    });
});
</script>
<html>
<body>
Name: <input id="name" type="text">
<p id="textboxvalue"></p>
</body>
</html>

Explanation

In Javascript or Jquery we need to do the explicit data binding by using DOM events like change,keypress etc. In the above example value typed in the Name textbox is updated in paragraph (textboxvalue) by using keypress jquery function.

Previous Topic : Advantages and Disadvantages of AngularJS
Next Topic : Built in angularjs directives part1

Advantages and Disadvantages of AngularJS

Key Features of AngularJS

Two-way data-binding

Two way data binding means automatic synchronization of data between the model and view components. Whenever the model changes,angular will cause the view to automatically update leading to no explicit DOM (Document Object Model) manipulation and vice versa. READ MORE

Minimal Code

AngularJS reduces the number of LOCs when compared to Javascript/JQuery.

Directives

At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) which attach a special behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.

Client side MVC framework

In Server side MVC framework, based on incoming client request the Controller existing at the server side retrieves the model and prepares the view which is sent back as a response to the client. While in Angularjs the client gets the response from the server as JSON data. The client browser parses the data to generate the model, creates the view templates and renders the page.

Dependency Injection

Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies. The Angular injector subsystem is responsible for creating components, resolving their dependencies, and providing them to other components as requested. It reduces the load on the backend and helps to create a lighter application.

Filters

A filter formats the value of an expression or transform input to an output for display to the user. They can be used in view templates, controllers or services.It is easy to define your own filter.

Templating

Angular combines the template with information from the model and controller to render the dynamic view that a user sees in the browser.

Deep Linking

Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.

Reduce the network traffic when compare to use server side scripting language like jsp,asp.

REST.

Integration Test Runner.

Form Validation.

Localization.

Cross browser support and no dependency on any external libraries.

Disadvantages of AngularJS

Client must enable JavaScript in the browser. Memory leak in JavaScript can even cause powerful system to slow down the browser. AngularJS works well only from Internet Explorer 8.0 onwards and doesn't support any older versions.


Previous Topic : What is AngularJS?
Next Topic : Two way data binding vs Traditional Approach

How to resolve VeraCode Improper Resource Shutdown or Release

Description

The application fails to release (or incorrectly releases) a system resource before it is made available for re-use. This condition often occurs with resources such as database connections or file handles. Most unreleased resource issues result in general software reliability problems, but if an attacker can intentionally trigger a resource leak, it may be possible to launch a denial of service attack by depleting the resource pool.

Recommendations

When a resource is created or allocated, the developer is responsible for properly releasing the resource as well as accounting for all potential paths of expiration or invalidation. Ensure that all code paths properly release resources.

For More detail - Improper Resource Shutdown or Release

Sample issue Code

import java.io.FileInputStream;
import java.io.IOException;
public class ResourceRelease {
  public static void main(String[] args) throws IOException {
   FileInputStream fin = null;
   try{
    fin = new FileInputStream("c:\\appv-instlog.txt");
   }catch(IOException e){
    e.printStackTrace();
   }  
  }
 }

Sample solution Code

import java.io.FileInputStream;
import java.io.IOException;
public class ResourceRelease {
  public static void main(String[] args) throws IOException {
   FileInputStream fin = null;
   try{
    fin = new FileInputStream("c:\\appv-instlog.txt");
   }catch(IOException e){
    e.printStackTrace();
   }finally{
    if(fin != null){
     fin.close();
    }
   }
  }
 }

Eligible Object for Garbage Collection when all the references of that parent object explicitly assigning to null

Overview

JVM will reclaim the unused object from heap memory for future use.Unused Object means no longer referenced by any part of your program pointer to that object. To demonstrate unused object is reclaim by garbage collector by calling System.gc() function.System.gc() method provides just a "hint" to the JVM that garbage collection should run. But It is not guaranteed!!

Parent object set to null

If an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.

Below Example - Garbage Collector will call when parent object references set to null

class EligibleParent{ 
  protected void finalize(){
   System.out.println("Parent Unused Object is reclaim by Garbage Collector.");
  }
}
class EligibleChild extends EligibleParent{
  protected void finalize(){
   System.out.println("Child Unused Object is reclaim by Garbage Collector.");
  }
}
public class EligibleParentNull {
  public static void main(String[] args) {
   EligibleParent obj = new EligibleChild();
   obj = null;
   System.gc();
  }
}

Output

Child Unused Object is reclaim by Garbage Collector.

Explanation

Above example System.gc() function is called after obj object set to null.Container object obj is null then contained object automatically becomes eligible for garbage collection.So the child class finalize method is called.

Note : Output Order may change based on System.gc() function calling the finalize method.

What is AngularJS?


Open Source Javascript Framework.

AngularJS is a structural framework for dynamic web application.

Perfect for Single Page Application (SPA).

It was developed in 2009 by Misko Hevery.

It is now officially supported by Google.

It extends HTML with new attributes.

There is no need of any server side Script like jsp,asp etc.

It can run anywhere where javascript can run because angularjs is completely written in javascript framework. Even supports many of the mobile browsers like Android,Chrome,safari etc.

It is entirely client side support framework.

It aims to simplify both the development and the testing of such applications by providing a framework for client-side model–view–controller (MVC) and model–view–viewmodel (MVVM) architectures, along with components commonly used in rich Internet applications.

It lets you to use HTML as a template language and to extend HTML syntax to elaborate your application components clearly and succinctly.

Prerequisite for learning angularjs is HTML,CSS and Javascript.

AngularJS Offical Site