Angularjs Directives

M2-R5.1 · Chapter 6: JavaScript and Angular JS · 2 min read

Angular js Directives

  • Definition: Directives are special markers in HTML that tell AngularJS to attach behavior or transform the DOM.

  • Built‑in Directives:

    • ng-app → defines the root of an AngularJS application.

    • ng-model → binds input fields to scope variables.

    • ng-bind → binds data to HTML elements.

    • ng-repeat → repeats an element for each item in a collection.

    • ng-if, ng-show, ng-hide → conditional display.

AngularJS Directives Example

1.ng-app

  • Defines the root of an AngularJS application

<div ng-app="myApp">

<p>AngularJS App Initialized!</p>

</div>

2.ng-init

Initializes variables.

<div ng-app="" ng-init="name='Aditya'; age=22">

{{ name }} is {{ age }} years old.

</div>

3.ng-model

Two Way Binds input fields to scope variables

<div ng-app="" ng-init="studentName='John'">

<input type="text" ng-model="studentName">

<p>Student: {{ studentName }}</p>

</div>

4.ng-bind

Binds data to HTML elements and displays data without Expressions( {{}}.)

<div ng-app="" ng-init="course='Computer Science'">

<p ng-bind="course"></p>

</div>

5.ng-repeat

Repeats elements for each item in a collection.

<div ng-app="" ng-init="students=['Amit','Ravi','Priya']">

<ul>

<li ng-repeat="s in students">{{ s }}</li>

</ul>

</div>

6.ng-if

Conditionally includes or removes elements.

<div ng-app="">

<input type="number" ng-model="marks">

<p ng-if="marks >= 50">Pass</p>

<p ng-if="marks < 50">Fail</p>

</div>