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>

View Comments

Recent Posts

Unveiling the Truth: Is the Spread of Sinus Infections a Myth or Reality?

Sinus infections, impacting approximately 31 million Americans each year, represent a significant health concern stemming…

1 day ago

Best Exercises To Reduce Weight & Keep You Stronger & Fitter!

No doubt that balanced weight is the key to wellness. So, when it comes to…

1 day ago

ARTIFICIAL INTELLIGENCE: Advantages And Disadvantages? Everything You Need to Know

Pros And Cons Of AI: Artificial Intelligence directly translates to conceptualizing and building machines that…

2 days ago

Four common mistakes when picking an internet provider

We all live on the internet; we use it for everything. Thus, when it comes…

2 days ago

What Is Commonly Misdiagnosed as Pink Eye: Understanding Eye Conditions and Their Symptoms

Introduction: Pink eye, or conjunctivitis, is a common eye condition characterized by redness and inflammation…

2 days ago

Why Flexible Financing is the Future of Small Business

Small businesses are the backbone of the economy. Still, they often face daunting hurdles when…

2 days ago