Sunday, 7 April 2013

AngularJS directive: Overview

During the last weeks, I gave an overview of most important features of the custom directives feature of AngularJS.
In this blog text, I’ll give a short overview of each of them.
  • template: You can replace the HTML element with a html fragment. It is most suited to add functionality (like validation) or use a short notation for a fragment you need multiple times. You can’t (see next) use the contents of the element in the result
  • transclude: With the tranclude property you can specify that you like to grab the content of the html element where the directive is placed on and use it on a certain location in the template html fragment.
  • compile function: instead of using a html template fragment, you can use the compile function to generate the required DOM changes in JavaScript. Compile function is the most suitable function when you need DOM changes.
  • options: with the attrs parameter of the compile function, you have access to the attributes defined on the element you used the custom directive on.  You can use it the configure your widget.
  • link function: If you need access to the model values defined in the scope object, you can use the link function of the directive.  Be aware that in case you perform DOM changes to your document, AngularJS expressions might not react anymore to the changes ion the model.
  • $watch: When you perform DOM changes in the link function and you need to react on changes in the model/scope object, you can use the function to restore the ‘binding’ again, programmatically.

In the last few weeks I gave an overview of the things that I learned when creating the AngularPrime library.

From using the simple attribute template to add functionality to the advanced usages of scope.$watch() to have the panel contents collapse programmatically.

Have fun with it.

No comments:

Post a Comment