DEV Community

Bethany Jones
Bethany Jones

Posted on

Common AngularJS Directives

One of the main criticisms of HTML and CSS is that it is static with very little interactivity. Web and app users these days expect to be able to dynamically change elements on a page with a click of a button and seamlessly transition between sections of the site or app. Additionally, many web applications are built as Single-Page-Applications (SPA) and/or use Model-View-Controller (MVC) architecture. All of that can be difficult to achieve with pure HTML, CSS, jQuery, and even JavaScript. Thankfully, there are libraries and frameworks that help address this issue, one in particular being AngularJS (not to be confused with Angular).

MVC & AngularJS

AngularJS uses a MVC approach to build single page apps. If you’re unclear on what MVC actually is, FreeCodeCamp’s sandwich metaphor might help clarify the concept. Essentially MVC architecture splits up your application into the model (data), the controllers (the middle man between the user and the system), and the views (the user interface/frontend that the user sees). While I won’t delve too deep into the benefits of MVC architecture, suffice it to say that AngularJS operates on a similar logic.

AngularJS Directives

The documentation refers to AngularJS as a “structural framework for dynamic web apps”(“What Is AngularJS?” AngularJS.Org). It expands the current HTML syntax through the use of directives that teach the browser new behaviors. It does this by adding new Directive attributes to DOM elements.

AngularJS has both pre-made directives and also allows us to create custom ones as well. While there are some 67+ directives listed on the AngularJS site, we’ll be going over some of the more common ones and breaking down the syntax and how to use them in your own projects.

Image description

<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<title>Learning AngularJS Directives</title>
</head>
<body>
<h2>Learning AngularJS Directives</h2>
<h5>AngularJS in Action</h5>
<p>With just a few extra snippets of code, we can turn a
static input form into something dynamic.</p>
<input type="text" ng-model="myName" placeholder="enter your name" />
<h5>Hello {{myName}}</h5>
<p>Thank you for joining us today on our journey through AngularJS.</p>
</body>
</html>

Some bootstrap code was removed for brevity and illustration purposes.

The above is a simple illustration of how easily we can incorporate dynamic elements in our applications. With just a few AngularJS directives (and a bit of Bootstrap), we were able to take a standard HTML form input and capture the values as they were typed and render them on the page in real time. Pretty nifty, right? Just wait until you see what else AngularJS can do.

Attribute Directives Syntax

Attribute directives are prefixed with ng- followed by the name of the attribute. These directives are used alongside other HTML attributes. Some common ones you’ll see covered here and elsewhere are ng-app, ng-click, ng-model, among others.

Data Binding Expressions

Similar to how JavaScript uses embedded ${expressions} as placeholders for data and can be used inside of HTML, so, too, does AngularJS. With AngularJS, we simply add an extra pair of curly braces: {{myName}}. Not only are we able to swap in data, we can also evaluate the expressions on the fly like you would in JavaScript. {{5 + 5}} would resolve to 10 and that would be what is displayed for the viewer.

Common Directives

ng-app
In the above example, we initialize the AngularJS app with a ng-app directive in the HTML lang tag, like so: <html lang="en" ng-app>. The ng-app designates the root element of the app allowing us to incorporate further directives throughout the code and using AngularJS as soon as the page is loaded.

ng-model
The ng-model directive is used to bind HTML form elements to a variable in the scope. This directive is only supported by <input>, <select>, and <textarea> elements. So, in the context of our example, we used the directive ng-model with a property name of "myName" to bind the value created by the input field to the {{myName}} expression used later in the code.

<input type="text" ng-model="myName" placeholder="enter your name" />

<h5>Hello {{myName}}</h5>

It was this directive that allowed the text to be displayed in the browser in real time as it was typed into the input field.

ng-init
This directive is used as a way to define some initial data, be it an array of names, a primitive value, or an object of key-value pairs. It is useful for demonstrating AngularJS’ capabilities as it allows us to see HTML elements change based on how we manipulate the initial data found in ng-init. However, more often than not, you will be using controllers or modules in the backend to do this instead. For now, let’s see ng-init in use.

<div ng-init="arrayName=['cats', 'dogs']">
<p>It is raining {{arrayName[0]}} and {{arrayName[1]}}.</p>
</div>

This code would display on the page as “It is raining cats and dogs.”

ng-repeat
Probably one of the more useful directives, ng-repeat lets you repeat lines of code without actually having to repeat lines of code. No more hard-coding <li> elements! It will render a set of HTML a given number of times, but can only be used on objects or arrays.

<div ng-init="array=[‘Birds’, 2, 100, ‘lions’, ‘pizza’]">
<li ng-repeat="element in array">{{element}}</li>
</div>

So, as we can see here, we use the ng-repeat directive in the element we want to see repeated, in this case a list item. We connect the directive to the data by using an arbitrary variable name (element), the keyword in, and most importantly the name of the array or object we want to iterate through (array), giving us ng-repeat="element in array". Then we use that same variable name in an expression ({{element}}) located where we want the data to appear. The directive will loop through the array or object until all elements have been rendered. And like magic, we will have a list of these array elements on the page.

Image description

**ng-click**
The last directive we will cover is the ng-click directive. Gone are the days of assigning clunky event listeners to key elements on your app. With the ng-click directive we can place it directly on any element we want to monitor for clicks. For example:

<h1 class="smiley">{{count}}</h1>
<button ng-click="count = count + '😄'" ng-init="count='😄'">Smile</button>

Image description

We used ng-init directive to set the initial value of count to 😄. Everytime there is a click on the button, the ng-click directive is evaluating the expression count = count + '😄' which is simply adding a 😄 to the variable count and reassigning the result to count. That then updates the {{count}} expression in the <h1> tag showing us the parade of emojis marching across the screen upon each button click.

There are dozens of other useful and powerful AngularJS directives for you to explore in more depth. To that end, here are some handy cheatsheets and guides to help you deepen your understanding of this framework. Happy coding out there.

Top comments (0)