Overview: AngularJS and Directives. What are they?

One of the great things about the AngularJS framework is how quickly you can go from concept to reality. AngularJS uses two-way data-binding to facilitate this. Rather than running through your business logic behind the scenes and then pushing rendered HTML to the browser, you are able to directly set variables in a template, which update immediately. This removes much of the legwork required in using tools like jQuery to manage the HTML on pages. And really, AngularJS doesn’t require you to use jQuery at all. But that also leaves you wondering how exactly you implement and manage more complex user controls in your web page.

You see, much of the magic that unfolds from AngularJS comes from controllers. These can be attached to sections of your HTML and are responsible for managing all of the content that is inserted into placeholders in your template. Controllers are excellent for use in organizing data and processing user feedback, but they are not well suited to directly managing the DOM (document object model, i.e. the HTML). So how are you supposed to utilize advanced controls like those found in the jQuery UI library? Directives provide everything you need to be able to implement these controls and keep your business logic concise.

Directives can easily be one of the most complex and daunting aspects of the AngularJS framework. What directives allow you to do is essentially extend the functionality of HTML tags and attributes. If I wanted to add a <datepicker> tag for use in my pages, I could write a directive that would understand that these tags represent places in the page where I need a field which utilizes the jQuery UI datepicker functionality. Directives are one of the most powerful concepts in AngularJS, but it’s not difficult to start writing them. The example I outlined can be written in fewer than 15 lines (here’s a working example, which is also embedded below) and what you get is a control that’s completely independent of the business logic of the page and can be reused across projects. They can be wrapped around virtually any jQuery plugin, but as the AngularJS framework matures, the community is writing more directives that are completely independent of jQuery as well.

Overview: AngularJS and Directives. What are they?

Leave a Reply

Your email address will not be published. Required fields are marked *