[javascript] What is an AngularJS directive?


1 Answers

Maybe a really simple and initial definition for angular directives would be

AngularJS directives (ng-directives) are HTML attributes with an ng prefix (ng-model, ng-app, ng-repeat, ng-bind) used by Angular to extends HTML. (from: W3schools angular tutorial)

Some examples of this would be

The ng-app directive defines an AngularJS application.

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

The ng-bind directive binds application data to the HTML view.

<div ng-app="">
    <p>Name: <input type="text" ng-model="name"></p>
    <p ng-bind="name"></p>
</div>

Check this tutorial , at least for me it was one of the best introductions to Angular. A more complete approach would be everything that @mark-rajcok said before.

Question

I have spent quite a lot of time reading through AngularJS documentation and several tutorials, and I have been quite surprised at how unapproachable the documentation is.

I have a simple, answerable question that may also be useful to others looking to pick up AngularJS:

What is an AngularJS directive?

There should be a simple, precise definition of a directive somewhere, but the AngularJS website offers these surprisingly useless definitions:

On the home page:

Directives are a unique and powerful feature available in AngularJS. Directives let you invent new HTML syntax, specific to your application.

In the developer documentation:

Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.

And there is a series of talks about directives which, ironically, seem to assume the audience already understands what they are.

Would anyone be able to offer, for clear reference, a precise definition of what a directive is that explains:

  1. What it is (see the clear definition of jQuery as an example)
  2. What practical problems and situations it is intended to address
  3. What design pattern it embodies, or alternatively, how it fits into the purported MVC/MVW mission of AngularJS.



In AngularJS Directives are html re markers for a HTML DOM element like an attribute(restrict- A), element name(restrict- E), comment(restrict- M) or CSS class(restrict - C) that tell AngularJS's HTML compiler ($compile) to perform a specified behavior to that DOM element or even transform the DOM element and its children.Some Example are ng-bind ,ng-hide/show etc.




Related