The first directive

In AngularJS, all the directives match the tag, element, or attributes name. The subsequent code demonstrates the varied ways in which a directive may be documented from a template. For example, myCustomDirective:

<my-custom-directive></my-custom-directive>
< !- - OR - ->
<span my-custom-directive></span>
< !- - OR - ->
<span class="my-custom-directive"></span>

Note

It is good practice to use tag names and attributes for directives instead of using elements and class names. Doing this typically makes it easier to see which directives matches a given element.

The following code example shows different options to invoke the directives:

<input type="text" ng-model=" my-Custom-Directive" placeholder="name" />
<span ng-bind=" my-Custom-Directive"></span>
<span ng:bind=" my-Custom-Directive"></span>
<span ng_bind=" my-Custom-Directive"></span>
<span x-ng-bind=" my-Custom-Directive"></span>
<span data-ng-bind=" my-Custom-Directive"></span>

In the AngularJS framework, directives are used for almost everything. As developers, we interact with the AngularJS framework through directives. These directives are the roots of the AngularJS framework. The AngularJS framework comes with built-in powerful directives, such as ng-repeat, ng-show, ng-if and so on, but sometimes, we need to create our own reusable custom directives.

The following code example shows how to structure an AngularJS custom directive:

var app = angular.module('myApp', []);

<!-- CONTROLLER -->
app.controller("ctrlSimpleDirective", function ($scope) {

});

<!-- DIRECTIVE -->
app.directive('mySimpleDirective', function () {
return {
template: '<div>This is a simple directive</div>'
}

});

To invoke the preceding directive, use the code shown as follows:

<div ng-controller="ctrlSimpleDirective">

<p my-simple-directive></p>

</div>

We can see in the preceding code that while invoking the directive name in the HTML <p> tag, it varies it is defined as mySimpleDirective. This is because AngularJS translates camel case into snake case. For example, mySimpleDirective will be translated to my-simple-directive. The preceding directive code does not do much. It just inserts <div>. This is a simple directive </div> into the <p> HTML tag.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset