Sunday, 26 April 2015

AngularJS Directives



AngularJS lets you extend HTML with new attributes called Directives.

AngularJS Directives:
AngularJS directives are extended HTML attributes with the prefix ng-.
The ng-app directive initializes an AngularJS application.
The ng-init directive initializes application data.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
<div ng-app="" ng-init="firstName='Ravi'">

<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>
The ng-app directive also tells AngularJS that the <div> element is the "owner" of the AngularJS application.

Data Binding:

The {{ firstName }} expression, in the example above, is an AngularJS data binding expression.
Data binding in AngularJS, synchronizes AngularJS expressions with AngularJS data.
{{ firstName }} is synchronized with ng-model="firstName".
In the next example two text fields are synchronized with two ng-model directives:
<div ng-app="" ng-init="quantity=1;price=5">

Quantity: 
<input type="number" ng-model="quantity">
Costs:    
<input type="number" ng-model="price">

Total in dollar: 
{{ quantity * price }}

</div>

Repeating HTML Elements:

The ng-repeat directive repeats an HTML element:
<div ng-app="" ng-init="names=['Ravi','Rahul','Chandan']">
  
<ul>
    
<li ng-repeat="x in names">
      
{{ x }}
    
</li>
  
</ul>
</div>
The ng-repeat directive used on an array of objects:
<div ng-app="" ng-init="names=[
{name:'Ravi',country:'Norway'},
{name:'Rahul',country:'Sweden'},
{name:'Chandan',country:'Denmark'}]"
>

<ul>
  
<li ng-repeat="x in names">
    
{{ x.name + ', ' + x.country }}
  
</li>
</ul>

</div>

The ng-app Directive:

The ng-app directive defines the root element of an AngularJS application.
The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.

The ng-init Directive:

The ng-init directive defines initial values for an AngularJS application.
Normally, you will not use ng-init. You will use a controller or module instead.

The ng-model Directive:

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
The ng-model directive can also:
  • Provide type validation for application data (number, email, required).
  • Provide status for application data (invalid, dirty, touched, error).
  • Provide CSS classes for HTML elements.
  • Bind HTML elements to HTML forms.

The ng-repeat Directive:

The ng-repeat directive clones HTML elements once for each item in a collection (in an array).


No comments:

Post a Comment