Aug 13, 2013

Angular.js – create reusable HTML widgets with directives

What is a directive?

Angular directives are a very powerful component of the Angular framework. They can control how the page is rendered in many different ways. Many of the attributes and tags built in to Angular are directives, such as ‘ng-show’, ‘ng-hide’, ‘ng-repeat’, etc. One way they can be used is to create HTML an widget that you can re-use across different partials.

How to create a simple directive

The Angular.js directive documentation goes into deep technical detail on how directives are implemented. This deep dive could be useful for complex directives, but it can obscure how easy it is to create simple directives. For example, suppose we want a re-usable HTML widget that messages displays to the user. The first thing we’ll do is create the directive:

As you can see, the code to define the directive is pretty minimal. The ‘scope: false’ tells Angular to not create a separate scope for the directive and just pass through the scope from the parent controller. And the ‘restrict: E’ says to only allow this directive to be used in an HTML element.

Next, let’s create the template body:

partials/widgets/messages.html:

Since we set ‘scope: false’ in the directive definition, errorMessage and successMessage are coming from the parent controller’s $scope. The controller code may contain something along these lines:

Finally, to use the new widget we just include this snippet in one of our partials:

And that’s a quick way to create a re-usable HTML widget with Angular.js.

About the Author

Object Partners profile.

One thought on “Angular.js – create reusable HTML widgets with directives

Comments are closed.

Related Blog Posts
Natively Compiled Java on Google App Engine
Google App Engine is a platform-as-a-service product that is marketed as a way to get your applications into the cloud without necessarily knowing all of the infrastructure bits and pieces to do so. Google App […]
Building Better Data Visualization Experiences: Part 2 of 2
If you don't have a Ph.D. in data science, the raw data might be difficult to comprehend. This is where data visualization comes in.
Unleashing Feature Flags onto Kafka Consumers
Feature flags are a tool to strategically enable or disable functionality at runtime. They are often used to drive different user experiences but can also be useful in real-time data systems. In this post, we’ll […]
A security model for developers
Software security is more important than ever, but developing secure applications is more confusing than ever. TLS, mTLS, RBAC, SAML, OAUTH, OWASP, GDPR, SASL, RSA, JWT, cookie, attack vector, DDoS, firewall, VPN, security groups, exploit, […]