Saturday 7 January 2017

AngularJS Directives

AngularJS Directives

AngularJS facilitates you to extend HTML with new attributes. These attributes are called directives.
There is a set of built-in directive in AngularJS which offers functionality to your applications. You can also define your own directives.
Directives are special attributes starting with ng- prefix. Following are the most common directives:
  • ng-app: This directive starts an AngularJS Application.
  • ng-init: This directive initializes application data.
  • ng-model: This directive defines the model that is variable to be used in AngularJS.
  • ng-repeat: This directive repeats html elements for each item in a collection.

ng-app directive

ng-app directive defines the root element. It starts an AngularJS Application and automatically initializes or bootstraps the application when web page containing AngularJS Application is loaded. It is also used to load various AngularJS modules in AngularJS Application.
See this example:
In following example, we've defined a default AngularJS application using ng-app attribute of a div element.
  1. <div ng-app = "">  
  2.    ...  
  3. </div>  
  4.   
  5.    

ng-init directive

ng-init directive initializes an AngularJS Application data. It defines the initial values for an AngularJS application.
In following example, we'll initialize an array of countries. We're using JSON syntax to define array of countries.
  1. <div ng-app = "" ng-init = "countries = [{locale:'en-IND',name:'India'}, {locale:'en-PAK',name:'Pakistan'}, {locale:'en-AUS',name:'Australia'}]">  
  2.    ...  
  3. </div>  

ng-model directive:

ng-model directive defines the model/variable to be used in AngularJS Application.
In following example, we've defined a model named "name".
  1. <div ng-app = "">  
  2.    ...  
  3.    <p>Enter your Name: <input type = "text" ng-model = "name"></p>  
  4. </div>  

ng-repeat directive

ng-repeat directive repeats html elements for each item in a collection. In following example, we've iterated over array of countries.
  1. <div ng-app = "">  
  2.    ...  
  3.    <p>List of Countries with locale:</p>  
  4.      
  5.    <ol>  
  6.       <li ng-repeat = "country in countries">  
  7.          {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}  
  8.       </li>  
  9.    </ol>  

AngularJS directives Example

Let's take an example to use all the above discussed directives:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.       <title>AngularJS Directives</title>  
  5. </head>  
  6. <body>  
  7.       <h1>Sample Application</h1>  
  8.         
  9.       <div ng-app = "" ng-init = "countries = [{locale:'en-IND',name:'India'}, {locale:'en-PAK',name:'Pakistan'}, {locale:'en-AUS',name:'Australia'}]">   
  10.          <p>Enter your Name: <input type = "text" ng-model = "name"></p>  
  11.          <p>Hello <span ng-bind = "name"></span>!</p>  
  12.          <p>List of Countries with locale:</p>  
  13.         
  14.          <ol>  
  15.             <li ng-repeat = "country in countries">  
  16.                {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}  
  17.             </li>  
  18.          </ol>  
  19.       </div>  
  20. <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>  
  21. </body>  
  22. </html>  
Test it Now

AngularJS Directives List

AnglarJS directives are used to add functionality to your application. You can also add your own directives for your applications.
Following is a list of AngularJS directives:
DirectiveDescription
ng-appIt defines the root element of an application.
ng-bindIt binds the content of an html element to application data.
ng-bind-htmlIt binds the inner HTML of an HTML element to application data, and also removes dangerous code from the html string.
ng-bind-templateIt specifies that the text content should be replaced with a template.
ng-blurIt specifies a behavior on blur events.
ng-changeIt specifies an expression to evaluate when content is being changed by the user.
ng-checkedIt specifies if an element is checked or not.
ng-classIt specifies css classes on html elements.
ng-class-evenIt is same as ng-class, but will only take effect on even rows.
ng-class-oddIt is same as ng-class, but will only take effect on odd rows.
ng-clickIt specifies an expression to evaluate when an element is being clicked.
ng-cloakIt prevents flickering when your application is being loaded.
ng-controllerIt defines the controller object for an application.
ng-copyIt specifies a behavior on copy events.
ng-cspIt changes the content security policy.
ng-cutIt specifies a behavior on cut events.
ng-dblclickIt specifies a behavior on double-click events.
ng-focusIt specifies a behavior on focus events.
ng-hideIt hides or shows html elements.
ng-hrefIt specifies a URL for the <a> element.
ng-ifIt removes the html element if a condition is false.
ng-includeIt includes html in an application.
ng-initIt defines initial values for an application.
ng-jqIt specifies that the application must use a library, like jQuery.
ng-keydownIt specifies a behavior on keydown events.
ng-keypressIt specifies a behavior on keypress events.
ng-keyupIt specifies a behavior on keyup events.
ng-listIt converts text into a list (array).
ng-openIt specifies the open attribute of an element.
ng-optionsIt specifies <options> in a <select> list.
ng-pasteIt specifies a behavior on paste events.
ng-pluralizeIt specifies a message to display according to en-us localization rules.
ng-readonlyIt specifies the readonly attribute of an element.
ng-requiredIt specifies the required attribute of an element.
ng-selectedIt specifies the selected attribute of an element.
ng-showIt shows or hides html elements.
ng-srcIt specifies the src attribute for the <img> element.
ng-srcsetIt specifies the srcset attribute for the <img> element.
ng-styleIt specifies the style attribute for an element.
ng-submitIt specifies expressions to run on onsubmit events.
ng-switchIt specifies a condition that will be used to show/hide child elements.
ng-transcludeIt specifies a point to insert transcluded elements.
ng-valueIt specifies the value of an input element.
ng-disabledIt specifies if an element is disabled or not.
ng-formIt specifies an html form to inherit controls from.
ng-modelIt binds the value of html controls to application data.
ng-model-optionsIt specifies how updates in the model are done.
ng-mousedownIt specifies a behavior on mousedown events.
ng-mouseenterIt specifies a behavior on mouseenter events.
ng-mouseleaveIt specifies a behavior on mouseleave events.
ng-mousemoveIt specifies a behavior on mousemove events.
ng-mouseoverIt specifies a behavior on mouseover events.
ng-mouseupIt specifies a behavior on mouseup events.
ng-non-bindableIt specifies that no data binding can happen in this element, or it's children.
ng-repeatIt defines a template for each data in a collection.

How to add directives

See this example:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5.   
  6. <div ng-app="myApp" w3-test-directive></div>  
  7. <script>  
  8. var app = angular.module("myApp", []);  
  9. app.directive("w3TestDirective", function() {  
  10.     return {  
  11.         template : "This is a directive constructor. "  
  12.     };  
  13. });  
  14. </script>  
  15. </body>  
  16. </html>  

AngularJS Expressions

In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and return the result exactly where the expression is written.
Expressions are written inside double braces {{expression}}.They can also be written inside a directive:
  1. ng-bind="expression".  
AnularJS expressions are very similar to JavaScript expressions. They can contain literals, operators, and variables. For example:
  1. {{ 5 + 5 }} or {{ firstName + " " + lastName }}  

AngularJS Expressions Example

  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <div ng-app>  
  6. <p>A simple expression example: {{ 5 + 5 }}</p>  
  7. </div>  
  8. </body>  
  9. </html>  
Test it Now
Note: If you remove the directive "ng-app", HTML will display the expression without solving it.
See this example:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <p>If you remove the directive "ng-app", HTML will display the expression without solving it.</p>  
  6. <div>  
  7. <p>A simple expression example:  {{ 5 + 5 }}</p>  
  8. </div>  
  9. </body>  
  10. </html>  
Test it Now
You can also write expressions wherever you want, AngularJS will resolve the expression and return the result.
Let's take an example to change the color of input box by changing its value.
See this example:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <p>Change the value of the input field:</p>  
  6. <div ng-app="" ng-init="myCol='pink'">  
  7. <input style="background-color:{{myCol}}" ng-model="myCol" value="{{myCol}}">  
  8. </div>  
  9. <p>AngularJS resolves the expression and returns the result.</p>  
  10. <p>The background color of the input box will be whatever you write in the input field.</p>  
  11. </body>  
  12. </html>  
Test it Now

AngularJS Numbers

AngularJS numbers are similar to JavaScript numbers.
  1.  <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <div ng-app="" ng-init="quantity=5;cost=5">  
  6. <p>Total in dollar: {{ quantity * cost }}</p>  
  7. </div>  
  8. </body>  
  9. </html>  
Test it Now
We can use the same example by using ng-bind:
See this example:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <div ng-app="" ng-init="quantity=5;cost=5">  
  6. <p>Total in dollar: <span ng-bind="quantity * cost"></span></p>  
  7. </div>  
  8. </body>  
  9. </html>                                                                                                                                                      
Test it Now

AngularJS Strings

  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <div ng-app="" ng-init="firstName='Sonoo';lastName='Jaiswal'">  
  6. <p>My full name is: {{ firstName + " " + lastName }}</p>  
  7. </div>  
  8. </body>  
  9. </html>  
Test it Now
Same example with ng-bind:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <div ng-app="" ng-init="firstName='Sonoo';lastName='Jaiswal'">  
  6. <p>My full name is: <span ng-bind="firstName + ' ' + lastName"></span></p>  
  7. </div>  
  8. </body>  
  9. </html>  
Test it Now

AngularJS Objects

  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <div ng-app="" ng-init="person={firstName:'Sonoo',lastName:'Jaiswal'}">  
  6. <p>My name is {{ person.firstName }}</p>  
  7. </div>  
  8. </body>  
  9. </html>  
Test it Now
Same example with ng-bind:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <div ng-app="" ng-init="person={firstName:'Sonoo',lastName:'Jaiswal'}">  
  6. <p>The name is <span ng-bind="person.firstName"></span></p>  
  7. </div>  
  8. </body>  
  9. </html>  
Test it Now

AngularJS Arrays

  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <div ng-app="" ng-init="points=[1,15,19,2,40]">  
  6. <p>The first result is {{ points[0] }}</p>  
  7. </div>  
  8. </body>  
  9. </html>  
Test it Now
Same example with ng-bind:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4. <body>  
  5. <div ng-app="" ng-init="points=[1,15,19,2,40]">  
  6. <p>The first result is <span ng-bind="points[0]"></span></p>  
  7. </div>  
  8. </body>  
  9. </html>  
Test it Now

Difference between AngularJS Expressions and JavaScript expressions:

  • AngularJS expressions can be written inside HTML, while JavaScript expressions cannot.
  • AngularJS expressions support filters, while JavaScript expressions do not.
  • AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.

Similarity between AngularJS Expressions and JavaScript expressions:

  • AngularJS expressions and JavaScript expressions both can contain literals, operators and variables.