Here you learn about Angular Directives, what are the different type of directives in angular framework. how to use them with html code, how to create custom directives in angular..etc.
AngularJS lets you extend HTML with new attributes called Directives, Directives in Angular is a js class, declared as @directive
.
AngularJS has a many built-in directives which ocan be used for functionality development in application, we also can make custom directives.
In AngularJs we have three different type of directives
Learn more about Angular directive
Here are some commonly used Angular Directives we use while developing single page web application
Root level element of an application.
Binds the data to a HTML element.
Specifies what should happen on blur events.
Specifies an expression to evaluate when user changing the content.
Specifies if checkbox is checked.
Specifies an expression to evaluate when any element is clicked
This directive is type of loop, it repeats data item and HTML element for each item in current collection.
Initialize application data for that a particular ng-app directive
Below are some examples of how to use angular directives in html code.
Here is an example of how you can write angular directives ng-init, ng-repeat within your html code
<div ng-app = "" ng-init = "countries = [{country:'India',currency:'INR'}, {country:'USA',currency:'USD'}, {country:'UK',currency:'GBP'}]"> <ol style="margin-left:50px;"> <li ng-repeat = "c in countries"> {{ 'Country: ' + c.country + ', currency: ' + c.currency }} </li> </ol> </div>
In above code you can see ng-repeat="c in countries"
,
here countries is the collection object declared and initialized in ng-init directive.
Things to notice
[{country:'India',currency:'INR'},{country:'USA',currency:'USD'}, {country:'UK',currency:'GBP'}]
Now you already know there are directives like *ngIf which is like if else statement in plain javascript, and *ngFor which is like for loop, so we learn how to use them with html DOM
Angular directive *ngIf example
<p *ngIf="!students"> <em>Loading student list... </em> </p>in above statement we are checking if student object is null.
Now in below statement, we will check if students object not null, then we loop through the collection and print each student details
<table class='table' *ngIf="students" > <thead> <tr> <th>Name </th> <th>Address </th> </tr> </thead> <tbody> <tr *ngFor="let s of students" > <td>{{ s.fullname }} </td> <td>{{ s.address }} </td> </tr> </tbody> </table>To simplify further, the above code says
if(students!=null) { foreach(student s in students) { console.write(s.fullname); } }
Hope you got some understanding of Angular directives and how to work with them in html code
You may be interested in following posts