AngularJS Directives


AngularJS, through what are calleddirectivesnew attributes to extend HTML.

AngularJS adds functionality to applications through built-in directives.

AngularJS allows you to define custom directives.


AngularJS Directives

AngularJS directives are extended HTML attributes with a prefix.ng-。

ng-appThe directive initializes an AngularJS application.

ng-initThe directive initializes application data.

ng-modelThe directive binds element values (such as the value of an input field) to the application.

For complete directive content, refer to theAngularJS Reference Manual。

AngularJS Example

<div ng-app="" ng-init="firstName='John'"> <p>Try typing in the input box:</p> <p>Name:<input type="text" ng-model="firstName"></p> <p>What you typed is: {{ firstName }}</p> </div>

Try it Yourself »

ng-appThe directive tells AngularJS that the <div> element is the AngularJSapplication's 'owner'.

Data Binding

In the above example, the{{ firstName }}expression is an AngularJS data binding expression.

Data binding in AngularJS synchronizes AngularJS expressions with AngularJS data.

{{ firstName }}It is throughng-model="firstName"that synchronization is performed.

In the next example, two text fields are synchronized using two ng-model directives:

AngularJS Example

<div ng-app="" ng-init="quantity=1;price=5"> <h2>Price Calculator</h2>Quantity:<input type="number" ng-model="quantity">Price:<input type="number" ng-model="price"> <p><b>Total:</b> {{ quantity * price }}</p> </div>

Try it Yourself »

Note Usingng-initis not very common. You will learn a better way to initialize data in the controllers chapter.

Repeating HTML Elements

ng-repeatThe directive repeats an HTML element:

AngularJS Example

<div ng-app="" ng-init="names=['Jani','Hege','Kai']"> <p>Use ng-repeat to loop through an array</p> <ul> <li ng-repeat="x in names"> {{ x }} </li> </ul> </div>

Try it Yourself »

ng-repeatThe directive is used on an array of objects:

AngularJS Example

<div ng-app="" ng-init="names=[ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sweden'}, {name:'Kai',country:'Denmark'}]"> <p>Loop over objects:</p> <ul> <li ng-repeat="x in names"> {{ x.name + ', ' + x.country }} </li> </ul> </div>

Try it Yourself »

Note AngularJS perfectly supports database CRUD (Create, Read, Update, Delete) applications.
Think of the objects in the example as records in a database.

ng-app Directive

ng-appThe directive defines the AngularJS application'sroot element.。

ng-appThe directive will, when the page has finished loading,automatically bootstrap(automatically initialize) the application.

Later you will learnng-apphow to connect to a code module using a value (such as ng-app="myModule").


ng-init Directive

ng-initThe directive defines for the AngularJS applicationinitial values.。

Usually, ng-init is not used. You will use a controller or module instead.

Later you will learn more about controllers and modules.


ng-model Directive

ng-modelThe directivebinds HTML elementsto application data.

ng-modelDirectives can also:

  • Provide type validation for application data (number, email, required).
  • Provide state for application data (invalid, dirty, touched, error).
  • Provide CSS classes for HTML elements.
  • Bind HTML elements to HTML forms.

ng-repeat Directive

ng-repeatFor each item in a collection (array), the directive willClone the HTML element once.。



Creating Custom Directives

In addition to AngularJS built-in directives, we can also create custom directives.

You can use the.directivefunction to add custom directives.

To invoke a custom directive, you need to add the custom directive name to the HTML element.

Use camelCase to name a directive, exampleDirective, but when using it, you need to-separate it with -,example-directive:

AngularJS Example

<body ng-app="myApp">

<example-directive></example-directive>

<script>
var app = angular.module("myApp", []);
app.directive("exampleDirective", function() {
    return {
template : "<h1>自定义指令!</h1>"
    };
});
</script>

</body>

Try it Yourself »

You can invoke a directive in the following ways:

  • Element name
  • Attribute
  • Class name
  • Comment

The following examples can also produce the same result:

Element name

<example-directive></example-directive>

Try it Yourself »

Attribute

<div example-directive></div>

Try it Yourself »

Class name

<div class="example-directive"></div>

Try it Yourself »

Comment

<!-- directive: example-directive -->

Try it Yourself »

Usage Restrictions

You can restrict your directive so that it can only be invoked by specific methods.

Example

By adding therestrictattribute and setting its value to"A", to set the directive so it can only be invoked by attribute:

var app = angular.module("myApp", []);
app.directive("exampleDirective", function() {
    return {
        restrict : "A",
        template : "<h1>自定义指令!</h1>"
    };
});

Try it Yourself »

restrictThe value can be one of the following:

  • EUsed as an element name
  • AUsed as an attribute
  • CUsed as a class name
  • MUsed as a comment

restrictThe default value isEA, which means the directive can be invoked by element name and attribute name.

Other extensions