AngularJS allows you to extend HTML with new attributes called directives. It comes with a set of built-in directives. However, you can create your own directives too.
AngularJS directives are custom HTML attributes with ng- prefix. With this prefix, it will allows AngularJS to recognize and process them accordingly.
In this tutorial, I will show you how to use the most common directives.
ng-app
<div ng-app="" ng-init="fruit='avocado'"> <p>My favorite fruit is {{ fruit }}.</p> </div>
ng-app directive lets AngularJS know that <div>
is the root element of the AngularJS application.
There can be only 1 ng-app per HTML document. ng-app directive is actually a module.
Currently, the module name is empty so that AngularJS will execute it automatically. Otherwise, you have
to call it manually as follows.
<div ng-app="myModule" ng-init="fruit='avocado'"> <p>My favorite fruit is {{ fruit }}.</p> </div> <script> var app = angular.module("myModule", []); </script>
Output
My favorite fruit is avocado.
ng-model & ng-bind
ng-model directive binds the value of an input field(e.g. <input>
, <select>
, <textarea>
) to a variable.
Think of ng-model as a way to declare a variable.
ng-bind directive binds the content of the HTML element to the model directive. Think of ng-bind as a way to link to the variable.
<div ng-app=""> <p>Type something in <input type="text" ng-model="myVariable"></p> <p>You have typed <span ng-bind="myVariable"></span>.</p> </div>
Output
Anything that you typed in the input field will be displayed back on the next line.
ng-init
ng-init directive initializes application data. Here are some examples.
<div ng-app="" ng-init="name='Joe'; fruits=['apple', 'pineapple', 'banana']"> <p>My name is {{ name }}.</p> <p>I love {{ fruits[1] }}.</p> </div>
Output
My name is Joe. I love pineapple.
ng-repeat
ng-repeat directive is used on an array or on an array of objects. It actually clones the HTML element for each item of the array.
Here is an example using ng-repeat directive to loop through an array.
<div ng-app="" ng-init="fruits=['apple', 'pineapple', 'banana']"> <p>List of fruits</p> <ul> <li ng-repeat="x in fruits">{{ x }}</li> </ul> </div>
Output
Here is an example using ng-repeat directive to loop through an array of objects.
<div ng-app="" ng-init="persons=[ {name:'Joe', age: 11}, {name:'Anne', age: 22}, {name:'Peter', age: 33} ]"> <p>{{ persons[0].name }} is {{ persons[0].age }} years old.</p> <ul> <li ng-repeat="x in persons">{{ x.name + ' is ' + x.age + ' years old.' }}</li> </ul> </div>
Output