Angularjs

AngularJS Directives


Angular JS directives are responsible for extending the functionality of HTML elements.Used to bind the view elements with the model.Usually, these are used in HTML code only as an element or attribute or class name or comment.

Element Vs Attribute

When the directive is used as an element we are creating a new HTML element itself and when used as an attribute we are enhancing the existing element.

Syntax

Directive as an element

 <ng-show></ng-show>

Directive as an attribute

<div ng-show></div>

Angular JS directives are HTML attributes prefixed with “ng”.We have many inbuilt directives and we can create our custom directives as well.

Before proceeding further let’s have an understanding of angular modules:

angular.module() is a function used for creating, registering and retrieving the Angular Js modules.All the modules that are available for the application must be registered using this function.

angular.module is a collection of controllers, services, directives, filters and configuration information.

 angular.module('appName',['requires'],['optional']);

Here appName is module name, the second parameter is an array of modules(dependencies) and the third parameter is configuration options which are optional. If we are using only first parameter (i.e, angular.module(“appName”))then we are referring to the predefined module or if we are including second parameter(‘[]’) as well then we are creating a new application module.


Angular Js Built in Directives


ng-app

Used to initialize/load the angular application and can be applied to any tag of HTML. Pay attention while applying it on any element, you might get an undefined module error if you didn’t include the angular.js library before using it.

This is the root element of the application where execution starts(application bootstraps) like the main method of Java.Ideally, there should only be one root app.

We can have more than one app in our code but only one app will behave as a starting point whichever defined first in the application.

Example:

<!DOCTYPE html>
<html>
<head>
<title>AngularJS with ng-app</title>
</head>
<body ng-app="mainApp" ng-controller="mainController">
<script>
var app = angular.module("mainApp",[]);
app.controller("mainController",function($scope){});
</script>
</body>
</html>>

NOTE: ‘mainApp’ is an optional parameter used to identify the application and second parameter ‘[]’ is to inject dependencies, by default it is empty.

Here, once the DOM is ready angular starts evaluating the script angular.js and looks for the ng-app directive.If the directive is found then it loads the module associated with it.

By default ng-app auto bootstraps the application.When we have multiple modules in a single page application one option is to manually bootstrap them and the other one is to inject them to the root app using dependency injection mechanism.

angular.bootstrap() function

First, let’s look at angular.bootstrap syntax:

angular.bootstrap(element,[module],[config]);

Here element can be any HTML element that will act as a root element for the application.The second argument is an array of modules to initialize and the third parameter is optional and used for configuration purposes.

NOTE: Module must be defined before manually bootstrapping it.If we are doing manual bootstrapping we should not use ng-app directive.

Let’s have two applications defined on two div’s and those are bootstrapped as below:

<body>
<div id="app1"></div>
<div id="app2"></div>
<script>
var firstApp = angular.module("app1",[]);
var secondApp = angular.module("app2",[]);
angular.bootstrap(document.getElementById('app1'),['app1']);
angular.bootstrap(document.getElementById('app2'),['app2']);
</script>
</body>

Injecting modules using Dependency Injection

We can define a root level app using ng-app this will be auto bootstrapped and later custom modules can be defined and injected into the root module.

<!DOCTYPE html>
<html>
<head>
<title>Multiple apps using dependency injection</title>
</head>
<body>
<div ng-app="rootApp">
</div>
<div ng-app="firstApp">
</div>
<div ng-app="secondApp">
</div>
<script>
/*Custom defined apps are injected into the rootmodule as dependencies*/
var rootapp = angular.module("rootApp",["firstapp","secondapp"]);
 angular.module("firstApp",[]);
 angular.module("secondApp",[]);
</script>
</body>
</html>

ng-init

It is used to initialize the application’s $scope data.It evaluates the expression and assigns the value to the $scope variable.Ideally, we should not use it for $scope’s data because there might be an ambiguity on whether the variable is initialized in the controller or in ng-init.

Recommended use of ng-init is to alias the code that is needed in view only. For example, there might be complex filter expression need to be applied to multiple elements on view then we can simply use that alias variable of ng-init expression and can be applied to multiple elements.

<!DOCTYPE html>
<html>
<head>
<title>Ng-init directive example</title>
</head>
<body ng-init="msg="Hello, Jhon!!!">
<div>
{{msg}} <p> How do you do??</p>
</div>
</body>
</html>

Here we used ng-init to initialize the $scope variable ‘msg’ and displaying it on the view itself as below:

Hello, Jhon!!! How do you do??

NOTE: We could not modify the variable initialized on ng-init expression through $scope object(i.e, in Controller).

ng-controller

we have also looked about ng-controller in the previous article.Each controller will be associated with the view on which it is applied.One such example could be to have a ng-controller on <body></body> element. Therefore body element will be able to access all the controller’s properties.

<!DOCTYPE html>
<html>
<head>
<title>ng-controller directive example</title>
</head>
<body ng-app="mainApp" ng-controller="mainController as ctrl">
<div>
{{ctrl.message}}
</div>
<script>
angular.module("mainApp",[]).controller("mainController",[function(){
this.message="Controller for body element"
}]);
</script>
</body>
</html>

Here we used “controller as” functionality that is basically used to access the controller’s properties.Using this approach would mean that the controller can define properties without required to push those on the $scope.

ng-model

This is used to bind applications input controls with the $scope of a controller.

<!DOCTYPE html>
<html>
<head>
<title>ng-model directive example</title>
</head>
<body ng-app="mainApp" ng-controller="mainController">
<input type="text" ng-model="message"><br>
<div>
{{message}}
</div>
<script>
angular.module("mainApp",[]).controller("mainController",['$scope',function($scope){
$scope.message="Am binded with input text box..My content will change with it"
}]);
</script>
</body>
</html>

Code Explanation:

The ng-model directive is applied on an input type textbox and initialized in the controller on $scope object.The variable assigned to the ng-model can be used on any element either by using ng-bind or by using Angular Js expression “{{}}“.Here we used it in div block using expression(“{{}}“).

 Try It!

ng-bind

This is used to bind ng-model data with other elements of the view.In the above example, we can have ng-bind on div instead of expression(“{{}}”) as below:

<!DOCTYPE html>
<html>
<head>
<title>ng-model directive example</title>
</head>
<body ng-app="mainApp" ng-controller="mainController">
<input type="text" ng-model="message"><br>
<div ng-bind="message">
</div>
<script>
angular.module("mainApp",[]).controller("mainController",['$scope",function($scope){
$scope.message="Am binded with input text box..My content will change with it"
}]);
</script>
</body>
</html>

 Try It!

Expressions

These are used to bind data to the View like the ng-bind directive. Angular JS introduced a special syntax to evaluate expressions like double braces:{{expression}}. These expressions are similar to javascript expressions can contain any literals, variables or operators.

Datatypes like Numbers, Strings, Arrays, and Objects can be evaluated with these expressions.

Examples:

Angular JS Numbers

<!DOCTYPE html>
<html>
<head>
<title>Angular JS Expressions-Numbers</title>
</head>
<body ng-init="num1=1;num2=2">
{{num1*num2}}
</body>
</html>

Output:2

Angular JS Strings

<!DOCTYPE html>
<html>
<head>
<title>Angular JS Expressions-Strings</title>
</head>
<body ng-init="firstName='Hello';lastName='Jhon'">
{{firstName+' '+lastName}}
</body>
</html>

Output: Hello Jhon

Angular JS Arrays

<!DOCTYPE html>
<html>
<head>
<title>Angular JS Expressions-Arrays</title>
</head>
<body ng-init="fruits=['apple','mango','orange']">
{{fruits[2]}}
</body>
</html>

Output: orange

Angular JS Objects

<!DOCTYPE html>
<html>
<head>
<title>Angular JS Expressions-Objects</title>
</head>
<body ng-init="Student={firstName:'Akhil',lastName:'D'}">
{{Student.firstName}}
</body>
</html>

Output: Akhil

ng-style

Used for styling the views dynamically through Angular JS code.Let’s see an example

<!DOCTYPE html>
<html>
<head>
<title>Angular JS ng-style directive</title>
</head>
<body ng-app="app" ng-controller="ctrl" ng-style="customStyle">
<p>My color is set with customStyle variable</p>
<script>
angular.module('app',[]).controller('ctrl',function($scope){
$scope.customStyle={
"background-color":"black",
"color":"yellow",
"text-align":"center",
"margin-top":'30%',
"font-size":'20px'
}
});
</script>
</body>
</html>

Here we applied ng-style on body element and setting its attributes like background color, color, and text-align.

 Try It!

ng-show/ng-hide

These directives are used to show or hide the view element based on its value.We can use these two interchangeably.

<!DOCTYPE html>
<html>
<head>
<title>Angular JS ng-show/hide directives</title>
</head>
<body ng-app="app" ng-controller="ctrl" >
<div ng-show="show" ng-style="styleText">Displayed using ng-show</div>
<div ng-hide="hide" ng-style="styleText">Displayed using ng-hide</div>
<script>
angular.module('app',[]).controller('ctrl',function($scope){
$scope.styleText = {
'font-size':'30px',
'text-align':'center',
'color' : '#00aabb',
'font-style':"bold",
'margin-top':'25%'
}
});
</script>
</body>
</html>

Applied ng-show and ng-hide on <div> elements and set show and hide variable initially with true. Since we had set both variables to true we are hiding the second <div> block and showing only first <div> block.

Try It!

ng-if

This is used to show or hide the element from the view but unlike ng-show/ng-hide it will completely remove the element from the DOM and recreates it.Here the view will be displayed only when the specified condition is met.

Like most of the directives, it will also rely on “true” or “false” values.It can also evaluate complex expressions that contain Javascript logical || and && operators.

<!DOCTYPE html>
<html>
<head>
<title>Angular JS ng-if directive</title>
</head>
<body ng-app="app" ng-controller="ctrl" >
<div ng-if="show">Condition evaluates to true</div>
<script>
angular.module('app',[]).controller('ctrl',function($scope){
$scope.show = "true";
$scope.styleText = {
'font-size':'30px',
'text-align':'center',
'color' : '#00aabb',
'font-style':"bold",
'margin-top':'25%'
}});
</script>
</body>
</html>

Here we had set the show variable to true.Therefore message in div block will be displayed.

 Try It!

ng-switch

This directive evaluates the expression and displays a child element that matches the expression.Here child element uses the ng-switch-when directive to match with the parent expression.If no element matches the expression then the ng-switch-default element will be displayed.

Example:

<!DOCTYPE html>
<html>
<head>
<title>Angular JS ng-switch directive</title>
</head>
<body ng-app="app" ng-controller="ctrl" >
<div ng-switch="myCity">
<div ng-switch-when = "Bangalore">Bangalore is IT city</div>
<div ng-switch-when = "Hyderabad">Hyderabad is famous for Dum Biryani</div>
<div ng-switch-default = "New Delhi">Capital city of India</div>
</div>
<script>
angular.module('app',[]).controller('ctrl',function($scope){
$scope.myCity= "Hyderabad";
});
</script>
</body>
</html>

Here depending upon the value of myCity variable div block will be displayed.Be aware while using the expression with ng-switch-when it will not evaluate the expression but takes the exact value within the quotes to compare with the condition.

 Try It!

ng-repeat

This is used to create the HTML elements by looping over an array of items.This is most commonly used for displaying lists.

<!DOCTYPE html>
<html>
<head>
<title>Angular JS ng-switch directive</title>
</head>
<body ng-app="app" ng-controller="ctrl" >
<ul ng-repeat="item in items">
<li>{{item}}</li>
</ul>
<script>
angular.module('app',[]).controller('ctrl',function($scope){
$scope.items = ["Angular2","AngularJS","Javascript","Bootstrap"];
});
</script>
</body>
</html>

Isn’t it look simple?Here we used ng-repeat to create a list of technologies, instead of creating a separate list item for each and every technology we pushed the technologies(list items) to an array and using ng-repeat creating the list on the fly.

 Try It!

ng-cloak

Used to prevent Angular JS HTML template to be displayed in uncompiled format while loading the application.It removes the undesirable flickering effect on the page.

It can be applied to any element and it has no value associated with it.

<p ng-cloak>Preventing flickering effect on page load</p>

ng-options

Used to populate options on the select input list.Works similar to ng-repeat but the benefit of using it over ng-repeat is it will be used to set non-string options in the list, whereas ng-repeat can be used on “option” element and it is bound to string value.

<!DOCTYPE html>
<html>
<head>
<title>ng-options example</title>
</head>
<body ng-app="myApp" ng-controller="myController">
<label>Select City : </label>
<select ng-model="selectedText" ng-options="item for item in items"></select>
<script>
angular.module("myApp",[]).controller("myController",function($scope){
$scope.items=['INDIA','USA','UK',];
});
</script>
</body>
</html>

Here ng-options is looping over items array and populating the list with the array items.Let’s understand the syntax:

ng-options=”label for item in array”

  • label” is used to create the option element
  • item” is the value associated with the option element
  • array” is the list of items to loop over

 Try It!

ng-include

This is used to fetch, compile, and include external HTML templates into our web page.Ideally included template must be located in the same domain as the referring document.These will be appended as child templates on the specified element.This can be used either as an attribute or an element.

syntax:

<div ng-include=”main.html”></div>

Example:

Create a HTML file named include.html as below:

<p> Included external template code</p>

Now let’s include it in our main.html file using ng-include

<!DOCTYPE html>
<html>
<head>
<title>ng-options example</title>
</head>
<body>
<div ng-include="include.html"></div>
</body>
</html>

Now when we run the file main.html we’ll get the result as “Included external template code”.

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *