DO YOU NEED A CONTENT WRITER FOR YOUR BUSINESS?

Your One-Stop Solution for All Content Needs! Click here for more!
Categories: AngularJS

AngularJS custom directives

Share

To extend the functionality of HTML in AngularJS, custom directives are used using “directive” function. This simply replaces the element for which this is activated.

Using its compile() method AngularJS application finds the matching elements and process for one time activity.

For the following types of elements AngularJS provides support to create custom directives.
– Element directives
– Attribute
– CSS
– Comment

Example:

<html>
<head>
<title>AngularJS custom directives</title>
</head>
<body>
<h2>AngularJS custom directives</h2>
<div ng-app="myApp" ng-controller="UserController">
<user name="John"></user>
<user name="Jane"></user>
<user name="Steve"></user>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var myApp = angular.module("myApp", []);

myApp.directive('user', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Name: <b>{{user.name}}</b>, Age: <b>{{user.age}}</b>";

directive.scope = {
user : "=name"
}

directive.compile = function(element, attributes) {
element.css("border", "1px solid #ffffff");

var linkFunction = function($scope, element, attributes) {
element.html("Name: <b>"+$scope.user.name +"</b>, Age: <b>"+$scope.user.age+"</b><br/>");
element.css("background-color", "#c2c2c2");
}
return linkFunction;
}

return directive;
});

myApp.controller('UserController', function($scope) {
$scope.John = {};
$scope.John.name = "John Doe";
$scope.John.age  = 47;

$scope.Jane = {};
$scope.Jane.name = "Jane Doe";
$scope.Jane.age  = 33;

$scope.Steve = {};
$scope.Steve.name = "Steve Martin";
$scope.Steve.age  = 25;
});

</script>
</body>
</html>
Namaste UI

For any types of queries, you can contact us on info[at]namasteui.com.

View Comments

Recent Posts

All You Need to Know about Low THC Oil Registry Card Georgia

Many of the states in the United States of America allow the use of medical…

5 days ago

Easy Ways to Strengthen Online Security and Privacy

Did you know that every time you browse this website or any other, you leave…

6 days ago

Play Anytime, Anywhere with GameZone Arcade Games

Online casino has gained immense popularity with the rise of online casinos. Platforms like GameZone…

1 week ago

Need to rank for seasonal keyword?

Every business has one or several peak seasons or periods of time during the year…

2 weeks ago

Himalaya Confido Results: What to Realistically Expect and When

Men searching for natural support often come across himalaya confido results — and the biggest question is…

2 weeks ago

Top Mutual fund houses and the differences between them

Looking to invest and get interest beyond your average savings account and fixed deposits? Well,…

2 weeks ago