There are many ways of creating reusable UI components in web, though in this article we will take a look into Angular JS' (version 1.*) approach.
Like any modern framework, Angular JS tries to make you code less and build more modular applications. It provides a clean MV* architecture for you to work with and in case you end up writing a jQuery selector in your controller, then it is time to use directives.
One of the advantages of Angular JS is that the framework does not invent anything new, but provides you with tools to extend basic HTML namespace with new tags and attributes. Thus, directives are the key to encapsulate any non-business logic into UI components and use them directly from HTML context.
Below is a usage example of a directive defined as an attribute.
<input type="text" uppercase-only />
The uppercase-only
attribute will turn a simple text input into field that displays only upper case characters. It'll automatically make the characters upper case when lower case entered. This directive may be useful for having credit card information, license numbers, etc in HTML forms.
The final directive source and JSFiddle are below.