AngularJS

Angular Directive Examples

Posted on Updated on

angularjs

What is Angular Directive?

It’s used to customized the functionality of HTML DOM element ( such as an attribute, element name, comment or CSS class ). Using Angular Directive we can create  own or customized the behavior of DOM elements.

Please read more about it here 

Before going to example section, let have a look on directive options:-

  • restrict :-
    • 'A' – only matches attribute name
    • 'E' – only matches element name
    • 'C' – only matches class name
    • 'AEC' – matches either attribute or element or class name
  • template :- HTML template inline
  • templateUrl :- URL of HTML template.
  • link :- Manipulate the DOM element.

Example 1 : “say-hello” Directive 

angular-example1

Output :- 

angular-example1-output

Example 2 : “myDirectiveAtts Directive 

This directive attribute simply bind DOM event and apply CSS on Div element.

angular-example2

Example 3 : “fileModel Directive for File Upload :

angular-example3

angular-example3-output
Render Page

Thanks !!

 

Advertisements

Simple Add Operation using AngularJS

Posted on

angularjs

Below are very simple example of AngularJS that Add two number. As discussed in “Introduction of AngularJS“, It’s  a powerful Javascript framework that is used to build a rich and dynamic web application.

In this example, we will see how to implement add operation using AngularJS. However, It is easy to write same program in Javascript or other client script language but it would be little bits hard for start-up to write using AngularJS. Here we will discuss code.

ng-app : Specify an AngularJS module to be used as the root module for the application.

Specify module name “dashboard” on root elements.

<html ng-app="dashboard">

Create an object of module “dashboard”.

var dashboard = angular.module("dashboard", []);

ng-controller : The ngController directive specifies a Controller class; the class contains business logic behind the application to decorate the scope with functions and values.

Here, module has controller component in AngularJS so create a Controller using controller name and callback function…

AddMe() is defined in button  inside ng-controller “myController” so it’s implementation would be under Controller block.

dashboard.controller('myController', function($scope) {
$scope.AddMe = function() {

var num1 = $scope.number1;
var num2 = $scope.number2;

$scope.result = parseInt(num1) + parseInt(num2);
};

ng-model :- Binding the view into the model, which other directives such as input, textarea or select require.
<input type="number" ng-model="number1">

Download AngularJS Framework from angularjs.org on your file system.

  1. Create a folder on your file system like AngularJSExample1
  2. Download AngularJS Framework and put “angular.min.js” under AngularJSExample1/js/
  3. Create a index.html file under root directory AngularJSExample1.
  4. Copy and paste below html code into index.html
  5. Save and run into browser…

 


<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<!--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script> -->

<script type="text/javascript" src="./js/angular.min.js"></script>
</head>
<body ng-controller="myController">
<h1>Welcome to AngularJS</h1>
<table border='1'>
<tr>
<td colspan='2'>
<h2>Arithmetic Operation</h2>
</td>
</tr>
<tr>
<td>Enter First Operand</td>
<td><input type="number" ng-model="number1"></td>
</tr>
<tr>
<td>Enter Second Operand</td>
<td><input type="number" ng-model="number2"></td>
</tr>
<tr>
<td>Result is</td>
<td>{{result}}</td>
<tr>
<td><input type="button" ng-click="AddMe()" value="Result"></td>
</tr>
<table>
</body>

<script>
var dashboard = angular.module("dashboard", []);

dashboard.controller('myController', function($scope) {
$scope.AddMe = function() {

var num1 = $scope.number1;
var num2 = $scope.number2;

$scope.result = parseInt(num1) + parseInt(num2);
};
});
</script>

</html>

Output here : –

angular-exm-001

Introduction of AngularJS

Posted on Updated on

angularjs

What is AngularJS ?

AngularJS is a powerful and structural JavaScript framework which is easier to implement in single web applications and allows organizing large, client heavy applications into something manageable. It is an open source web application framework, free and used by thousands of developers around the world.

AngularJS is based on the MVC(Model View Control) pattern that is intended to build rich internet web applications and simplify both development and testing of applications by using MVC architecture and separating your rich internet applications into models, views and controllers. AngularJS creates single page applications, which means the browser is going to load a single page regardless of the size of your application.

AngularJS was developed by Miskohevery and Adam Abron, maintained by Google; used internally by them and MIT. It is licensed under the Apache License version 2.0. It was initially released in 2009 and the current stable release is 1.3.x (Decemeber 1, 2014).

 

AngularJS: In this section, let us summarize the basics of AngularJS.

  • Is a library written in JavaScript
  • Is not a platform or language
  • Is not a plug-in or extension
  • It extends HTML, CSS and JavaScript
  • Is not a DOM manipulation library like jQuery
  • Does not require jQuery or inheritance
  • Does not require one-way data binding and boilerplate code

Why AngularJS?

  • It is based on MVC design pattern which provides numerous ways to build web application at client side.
  • It helps to build client side applications with less code and more flexibility.
  • It extends HTML by using functionality of directives, attributes, expressions and templates to HTML.
  • AngularJS is a MVC architecture which simplifies the development and testing of applications easily for client side.
  • It is good for developing single page applications and front ends for web based applications.
  • It has flexible framework and versatile features. So it is used for both large app projects and small little applications.

Features:

AngularJS (JavaScript based framework) creates applications in a faster way by using several features such as:

  • It is a client side technology which provides powerful things to create dynamic web applications.
  • It is a MVC based framework, allows users to build proper architecture and maintainable web applications.
  • It is an open source web application framework used by thousands of developers around the world.
  • It allows use of reusable components and code reuse.
  • It makes creation of user interface (UI) easy through data binding process.
  • Declarative HTML approach.
  • It helps to divide your application into smaller parts.

Architectural Diagram and Components: Let us have a look at the architecture diagram of the AngularJS framework and its components.

angular-js-architecture

AngularJS contains modules which act as a container for different types of applications such as controllers, views, directives, factory etc. Module specifies how an application should be bootstrapped. Using modules, processes will be easier to understand; you can reuse the code, end to end tests uses modules to override the configuration etc. It is the place for creating, registering and retrieving angular modules.

Config component only accepts providers from modules, means every service, factory etc are instances of provider. It provides all these instances to routes.

The Routes are used for linking URL’s to controllers and views.

The Views are used to add sophisticated handling of user events. It uses ng-view directive that complements route service by template of the current route to the main layout (index.html) file.

The controller controls the data of AngularJS applications which are regular JavaScript objects. AngularJS defines ng-controller directive which creates new controller objects by using controller function. And new child is available to the controller function as $scope as shown in the diagram.

The views sends element or attribute to the directives which tells AngularJS’s HTML compiler to attach specific behavior to the DOM element and its children.

The factory is used to define the AngularJS service and it is called when a service needs to be instantiated.

Getting Started with AngularJS:

AngularJS is easy to start with. It provides features like two way data binding which makes custom tags, attributes which encapsulate built-in directives that make extending functionality of HTML easier.

  • It is distributed JavaScript file and can be used in a webpage by including AngularJS library as shown below:

<script src=”http:// ajax.googleapis.com/ajax/libs/ angularjs /1.2.26/ angular.min.js”>

</script>

You can also check the latest version of AngularJS on their official website.

  • You can create AngularJS application as shown below:

<htmlng-app></html>

Or

<html ng-app=”MyApp”></html>

Or

<divng-app></div>

Or

<div ng-app=”MyApp”></div>

 

The ng-app attribute is the root element of the AngularJS app.

  • Controller can be defined as shown below:

<div ng-app=” “ ng-controller=”MyController”>

<input type=”text” ng-model=”message”>

</div>

The ng-controller directive defines the application controller. The ng-model directive binds the value of HTML controls such as input fields, select etc to the application data.

  • Implement the controller by using $scope object as written below:

functionMyController($scope){

$scope.message=”Enter your name”;

}

The $scope object refers to the application model which invokes the controller that creates messageproperty in the scope.

Core Concepts: In this section we will have a detailed discussion about the core components and the concepts behind them.

  • Modules
  • Directives
  • Scope
  • Controllers
  • Expressions
  • Templates
  • Routing
  • Filters

Modules:

Modules provide excellent mechanism for dividing the application into small reusable components and specify how an application should be bootstrapped. Modules specify how you define the components in the application and makes application more readable. Each module is identified by a unique name.

Directives:

Directives are core building blocks of AngularJS which are used to create custom HTML tags and can be placed in element names, attributes and comments. Directives can be used as HTML directives which build complex widgets with layered functionality.

Scope:

Scope is an object that binds a view to the controller. In MVC structure, it refers to the application model. Scopes can watch expressions and propagate events as they are arranged in hierarchical structure.

Controllers:

Controllers are JavaScript objects that defines the actual behavior of your app. It is responsible for setting model properties and functions by using $scope object. The controller does not store state and does not interact with remote services.

Expressions:

Expressions are written inside curly braces “{{   }}” denote bindings which referrers to our application model. Expressions do not support control flow statements. AngularJS will output the data where they are used.

Templates:

Template is just old-plain-HTML that does not include any angular specific file templates. It comes with a set of live templates to create controllers etc by using template engine. Templates are used to show information from the model and controller.

Routing:

It is used for linking URL’s to controller and views. Routing is taken care by service providers called$routeProvider to handle routing which is the provider of the $route service. In other words, it’s loading of sub templates depending upon the URL of the page.

Filters:

Filters are used with expressions to transform or modify the data from the models. We can add expressions or directives using pipe character. AngularJS has some of the commonly used filters such as:

  • currency: converts number to currency format.
  • uppercase: converts strings to uppercase.
  • lowercase: converts strings to lowercase.
  • filter: selects subset of items from array.
  • orderBy: orders array by the expression such as ordered alphabetically for strings and numerically for numbers.

Example:

Let’s create one simple example using AngularJS library and create a HTML file as FirstExample.html as shown below:

Listing1: Simple AngularJS application


<!DOCTYPE html>

<html>

<head>

<script src= “http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js”></script>

</head>

<body>

<div ng-app=”” ng-controller=”MyController”>

Enter Name: <input type=”text” ng-model=”userName”><br><br>

Full Name: {{userName}}

</div>

<script>

functionMyController($scope) {

$scope.userName = “David”;

}

</script>

</body>

</html>

As discussed, we have included AngularJS JavaScript file in the HTML page which is defined within the <head> tag. The next part contains AngularJS app which is defined using the ng-app attribute runs inside the <div> tag.

The ng-controller directive defines the application controller. The AngularJS will invoke the “MyControllerwith $scope object which creates property called “usernamein the scope.

Define the model name using ng-model directive defined in the <input> tag. It binds the input field to the controller property “username”.

 

Example here :-

  1. Add two number using AngularJS
  2. Arithmetic Operation using AngularJS.