AngularJS lets you extend HTML with new attributes called Directives. These are special attributes starting with ng- prefix. In this article we will learn about ng-app, ng-init, ng-model and ng-repeat. Following are the brief introductions of all these 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.
Understanding ng-app directive with example in AngularJS
ng-app directive starts an AngularJS Application. ng-app is used to define the root element. The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.. ng-app is also used to load various AngularJS modules in AngularJS Application. Let’s consider following example, we've defined a default AngularJS application using ng-app attribute of a div element.
The ng-app directive also tells AngularJS that the
element is the "owner" of the AngularJS application.
Understanding ng-init directive with example in AngularJS
ng-init directive initializes an AngularJS Application data. It is used to put values to the variables to be used in the application. Normally, we will not use ng-init. We will use a controller or module instead. Let’s consider following example, in this example we will try initialize an array of students. We're using JSON syntax to define array of students.
...
Understanding ng-model directive with example in AngularJS
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data. There are following functions of ng-model directive, which can be very useful in AngularJS application development.
- 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.
Let’s consider following example, we have defined a model named "name".
Understanding ng-repeat directive with example in AngularJS
ng-repeat directive repeats html elements for each item in a collection. In other words we can say that, the ng-repeat directive clones HTML elements once for each item in a collection (in an array). Let’s consider an example, we have iterated over array of students.
...
List of Students with Roll Number:
-
{{ 'Student Name: ' + student.name + ', Roll Number: ' + student.rollnumber }}
Summary:
In this article we have learn about Angular JS Directive. It is very important to understand these directive, because it is not possible to go further to learn Angular JS without the knowledge of Angular JS directive. It is suggested to read Angular JS Expressions. I hope you will like this article and now you are able to start with AngularJS easily.