Monday, 25 April 2016

What are the directives in AngularJS ?

Directives in AngularJS

ng-app
Attach module to the page
<html ng-app="module1">

ng-controller
Attach a controller function to page
<body ng-controller="moduleController1 as c1">

ng-show
Display a section based on expression
<h1 ng-show="c1.product.isPurchasable">Yes, You can buy it</h1>

ng-hide
Hide a section based on expression
<h1 ng-hide="c1.product.isOutOfStock">Product 1</h1>

ng-repeat
Repeat a section for each item in array
<li ng-repeat="prd in c1.products">{{prd.name}}</h1>

ng-src
Includes source for images using Angular expressions
<img ng-src="{{prd.photo}}" />

If you use Angular expression inside src attribute, it will give error :
<img src="{{prd.photo}}" />
because, browser will try to load image before evaluating the expression.

ng-init
Initialize value on load

ng-click
Sets value on click
<section ng-init="tab = 1">
<ul class="nav nav-pills">
   <li> <a href ng-click="tab = 1">Account</a> </li>
   <li> <a href ng-click="tab = 2">Payments</a> </li>
   <li> <a href ng-click="tab = 3">History</a> </li>
</ul>
{{tab}}
</section>

On initialization, sets tab = 1 which shows first tab.
Then on click of the tab, assigns the new value and print value on screen.
On refresh, again initial tab is set.

2-way data binding
When click on second tab, it will print "2" on screen, and monitored for next change of its value and then updated on screen.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.