AngularJS Directive with Our First AngularJS Example

AngularJS Directive with First AngularJS Example:

We had a brief introduction to AngularJS in our previous tutorial. This tutorial will explain you the important facts that you need to know about AngularJS.

AngularJS is an open-source web application framework based on JavaScript.

It is maintained by Google Corporation and a big community. AngularJS is an answer to the various drawbacks that are encountered to formulate single-page applications. 

Read through our Entire AngularJS series for in-depth knowledge on AngularJS concept.

AngularJS Directive and Example

AngularJS application framework acts as a template and can reduce the challenges that are faced during the development of web apps.

Overview of AngularJS

AngularJS was released by Google on 20th October 2010, and today it has become a significant framework for various single-page interface applications.

That’s is the reason for which AngularJS has held its ground in spite of technological developing at a breakneck pace. The cross-platform interface based system makes it more efficient too.

AngularJS complements and benefits the Apache Cordova, which is a framework that is used for cross-platform mobile apps. It has a vision of bettering the experience and simplifying the testing and development of web apps and provides a robust framework for their AngularJS application development.

Why Use AngularJS?

Enlisted below are the various features and reasons for which AngularJS should be used in the web application development.

  1. Data Binding: The platform provides automatic sync of data between the model and view contents and as a result, it saves your time as well as the effort to a great extent.
  2. Controller: These are JavaScript that is bound to a particular scope.
  3. Services: AngularJS has many built-in services. E.g $https
  4. Filters: This helps in selecting a subset of items from an array and returns it to a new array.
  5. Directives: They are markers on DOM elements like attributes, CSS elements, etc. These can be used as custom tags of HTML.
  6. Routing: Helps in creating single page applications. It is specified in the URL after the # sign and enables you to create different URLs for different content in your application.
  7. MVC: Stands for Model, View, and Controller. It is a design pattern and is used for the division of an app into different parts, i.e., Model, View, and Controller.
  8. Deep Linking: This feature of the app framework helps you to encode the state of the application in the URL for bookmarking. Later, the app can also be restored from the URL in the same state.
  9. Dependency Injection: AngularJS also has an in-built dependency injection sub-system which can be helpful for the developer to make the process of development and testing easier, cohesive and straightforward.
  10. Scope: These are the objects that act as a glue between the controller and the view.

How to Use AngularJS?

Personally, I believe that there is hardly any better front-end web app developing framework that is available in the market today than AngularJS.

The tutorials on how to use AngularJS are not frustratingly complex, and I indeed found them quite easy to follow as well. You can take advantage of a two-way binding system, templating facilities, modularization, dependency injection system, AJAX Handling function and the other features of this framework too.

Before initiation of coding, you should know about the MVC concept (Model, View, and Controller), the “Hello World” script, and the various features of AngularJS.

AngularJS Directives

AngularJS provides you with a large number of directives that enable you to associate the various HTML elements with application data. They are the basic attributes that start with the keyword ng-.

The most important directive that you must include on any page while using AngularJS is given below.

ng-app - <body ng-app> 

It is the starting point of the AngularJS application and must be added to any element that envelops the rest portion of the page, like the body part element. AngularJS looks for this aspect whenever the page loads and tends to evaluate all the various directives in the code automatically.

The directives of AngularJS include:

#1) ng-app: This is used to start the AngularJS application. When the web page containing AngularJS application is loaded, it automatically bootstraps the application by defining the root element. Only one ng-app directive should be used in your HTML code.

However, if more than one ng-app directives are found in the HTML code, then the first appearance will be used.

Syntax:

<div ng-app=”name of your application”>
{body of the HTML code}
</div>

#2) ng-init: This is used to initialize the application.

It provides a set of values that have to be associated with variables for initializing purposes. This directive is not often used as initialization of variables usually happens through specific functions within the project.

Syntax:

<div ng-app=”name of your application” ng-init=”variable name=[{value a1,value a2},{valueb1,valueb2},……..
{body of the HTML code}
</div>

#3) ng-controller: It is used when initialization of variables has to be done based on a function; i.e., each of the variables has to be initialized based on function logic. AngularJS invokes the function specified in the ng-controller directive with an object.

Syntax:

<div ng-app=”name of your application” ng-controller=”name of your function”>
</div>

<script>
app.controller(‘name of your function’,function($object){
Body of the controller/function});
</script>

#4) ng-model: This is used to bind the values of AngularJS to the controls provided by the application. To be specific, the data fetched by the input through the controller and the model will be bound to the view (w.r.t. MVC model) that will be presented to the user.

Syntax:

<div ng-app=” name of your application” ng-controller=”name of your function”>
Your Variable to be binded : <input ng-model=” input”>
<h1>You entered:{{input}}</h1>
</div>

The head field h1 used will help in two-way binding, i.e., if the user changes the value inside the input field, the AngularJS attribute will also change. If the property in ng-model does not exist, AngularJS itself will create one.

There are various other applications of the ng-model directive such as type validation, application status and provision of CSS classes for HTML elements.

Example:

<form ng-app=”” name=”myForm”>

Email: 
<input type=”email” name=”myAddress” ng-model=”text”>
<span ng-show=”myform.myAddress.$error.email>Not a valid e-mail address</span>
</form>

When you run this code, the webpage will have a field called “Email:” and it returns the error message displayed in the span tag when you try to input invalid datatypes that aren't configured for that variable.

Depending on the application status, the ng-model provides CSS classes for HTML elements. The various classes such as ng-empty, ng-not-empty, ng-touched, ng-untouched, ng-valid, ng-invalid, ng-dirty, ng-pending and ng-pristine will be added or removed by the ng-model directive based on the status of the form field.

#5) ng-repeat: It is used in the repetition of HTML elements for each item in the collection. The set of HTML will thus be repeated once per item within the collection. This directive is often used for creating tabular datasets.

Syntax:

<div> ng-app=”” 
 <p>Example list</p>
<ol>
<li ng-repeat=”name of your list”>
{{‘Element1 : + array.item1 +’ , ‘Element2 : + array.item2 +’}}
</li>
</ol>
</div>

{Body of the HTML code}

Other Important Directives

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angular/1.6.9/angular.min.js">
</script>

<body>
<div ng-apps="">
<p>Name: <input type="text" ng-model="name"></p>
<p>You wrote:{{ name}}</p>
</div>
</body>
</html>

ng-class: It binds one or more CSS classes to an HTML element in a dynamic manner.

<select ng-model="home">
<option value="sky">Sky</option>
<option value="tomato">Tomato</option>
</select>

<div ng-class="home">
<h1>Welcome Home!</h1>
              <p>I like it!</p>
</div>

ng-animate: This directive helps in supporting the animation – the transformation of an HTML element to give the illusion of motion, including CSS3 transitions, CSS3 keyframe animation as well as JavaScript.

<body ng-app= "myApp">
<h1> Hide the DIV: <input type= "checkbox" ng-model= "mycheck"></h1>

<div ng-hide= "mycheck"></div>

<script>
var app = angular.module('myApp', ['ngAnimate']);
</script>

ng-show and ng-hide: These commands hide and show the elements, that is achieved by setting the CSS display style.


AngularJS also lets you define Custom directives. They are used to extend the functionality of HTML and are defined using the “directive” function. They simply replace the element for which they are activated.

The AngularJS Cheat Sheet was a life saver for me. There are a number of other guidelines that you can check on the Cheat Sheet. You can even learn how to build custom directives via the use of AngularJS. I found all the instructions and directives of the AngularJS platform on the Cheat Sheet to simplify many issues.

AngularJS Example

A simple AngularJS example can be written as follows:

You need to create an HTML file, For Example, angularjsexample.html as shown below.

<!doctype html>
<html>

<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js">
</script>
</head>

<body ng-app = "myapp">

<div ng-controller = "HelloController">
<h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
</div>

<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
</script>

</body>
</html>

In the above Example, the script <script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js”></script> represents AngularJS JavaScript.

You would be surprised to know how many apps that you use daily have been developed on the AngularJS platform.

Here are a few names:

  • The Guardian
  • PayPal
  • jetBlue
  • Lego
  • Upwork
  • Netflix
  • Freelancer
  • iStock

It is evident from the names above as what height you can reach by learning to utilize this framework. These sites are at the top of their game, and a huge part of their success definitely goes to the efficiency of the sites just because they have been developed on AngularJS.

Conclusion

If you are looking to build and develop single-page apps for mobile or even websites, like how I was once – then look no further.

AngularJS is a one-stop shop for you, as this site helps and makes the development of applications much more comfortable and cohesive. It is not just great for beginners, but as you delve deeper into it, you will tend to learn with experience and develop great apps.

Meanwhile, in case you upgrade to more recent versions, then you don’t need to put in a lot of efforts. Just by learning a few new commands and understanding new tweaks, you can start developing applications in the new versions too.

Watch out our upcoming tutorial to know more about developing single page web applications using AngularJS.

PREV Tutorial | NEXT Tutorial