Pippo's blog

it is all about software development

AngularJS: directives

A fair amount of web developers that start using AngularJS have previous experience with jQuery and a jQuery like solution is what come first to their minds when they see a problem that require some changes to the DOM elements. This is still true for myself as well.

What we need to keep in mind is that angular provide a very interesting way of manipulating DOM elements, a reusable and sophisticated way. They are called directives.

Why do I need directives?

The first motivation is that attaching events to elements that don’t exist make your app to not work the way you think it should =)

Hold on! What? Non-existing elements?

As we make use of angular bindings, we let the framework create and destroy DOM elements - elements inside a ng-repeat, for example, are not visible to JS code at $(document).ready() time. Sounds familiar?

Directive is a component triggered by the time your DOM element become part of the page, which is than the right time to attach to events or do further processing related to that element.

If you are a little scared about the directive’s documentation and overloaded by all things it can handle, take a look at a simplified version of it first and then learn more about it in depth and how to use it to expand templates, do animations, listen to events…

Comments