Using link function in directives

Loading

1. What is the link Function in AngularJS Directives?

The link function in an AngularJS directive is used for DOM manipulation and handling event listeners.

Why Use the link Function?

✔ To interact with the DOM after the directive is compiled.
✔ To add event listeners (e.g., click, hover).
✔ To modify attributes or styles dynamically.


2. Syntax of the link Function

link: function(scope, element, attrs) {
// DOM Manipulation here
}
ParameterDescription
scopeProvides access to the directive’s scope.
elementA jQuery-wrapped object of the directive’s element.
attrsContains all attributes applied to the directive.

3. Basic Example – Changing Text on Click

Directive Code (JavaScript)

var app = angular.module("myApp", []);

app.directive("clickChange", function () {
return {
restrict: "A",
link: function (scope, element, attrs) {
element.bind("click", function () {
element.text("Text Changed on Click!");
});
}
};
});

HTML Usage

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">
<p click-change>Click me to change text!</p> <!-- Applied as an attribute -->
</body>
</html>

Explanation:

When the user clicks the <p> tag, its text will change dynamically.


4. Example – Changing Background Color on Hover

Directive Code (JavaScript)

app.directive("hoverHighlight", function () {
return {
restrict: "A",
link: function (scope, element, attrs) {
element.bind("mouseenter", function () {
element.css("background-color", "yellow");
});
element.bind("mouseleave", function () {
element.css("background-color", "white");
});
}
};
});

HTML Usage

<div hover-highlight style="padding: 10px; border: 1px solid black;">
Hover over me!
</div>

Explanation:

Mouse enter → Background turns yellow.
Mouse leave → Background turns white again.


5. Example – Accessing Attributes (attrs)

Directive Code (JavaScript)

app.directive("customMessage", function () {
return {
restrict: "A",
link: function (scope, element, attrs) {
element.text(attrs.customMessage);
}
};
});

HTML Usage

<p custom-message="Hello from Attribute!"></p>

Explanation:

The directive reads the custom-message attribute and sets its value as text inside <p>.


6. When to Use the link Function?

For DOM Manipulation (Changing text, colors, adding/removing elements).
For Event Handling (click, hover, keydown, etc.).
For Accessing Attributes dynamically.

Leave a Reply

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