Open In App

Difference between link and compile in AngularJS

Last Updated : 21 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see the link and compile features in Angular JS, along with understanding their implementation through the illustration and exploring the key differences between them.

One of the fundamental components of AngularJS is the directive. When creating web components, a directive enables declarative HTML vocabulary expansion. Attributes, tags, class names, comments, etc, are all examples of directives. With its many built-in directives, Angular makes it simple for users to build and manage different functionality in their applications. The Link in AngularJS usually utilizes to customize the DOM elements with help of Custom Directives, whereas the Compile is utilized to compile the HTML string or the DOM element & convert it into the template, & correspondingly produce the template function, that is used to link the scope and the template together. We will explore & understand how the Link & Compile is related to Directives in Angular JS.

Link: The link function is essentially used to manipulate the DOM(Document Object Model). The link option in the custom directive updates the DOM and registers a DOM listener. It creates a live view by fusing the directives and a scope. Both user interactions with the view and changes to the scope model, and are reflected in the views and vice versa. The link function is used to establish our bindings to the page and register all the listeners on a particular DOM element (which is copied from the template).

 

Syntax:

angular.module("myApp", [])
    // Registering custom directive
    .directive('myProduct', function () {
        return {
            ... 
            link: function(scope, element, attrs, 
            controller, transcludeFn) {
                // Write your code here...
            }
            ...
        };
    });

Example: This example describes the basic usage of the Link in Angular JS.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8" />
    <title>AngularJS Link</title>
    <script>
        document.write('<base href="' + document.location + '" />');
    </script>
    <style>
        body {
            font-size: 20px;
        }
    </style>
    <script data-semver="1.4.9" 
            src="https://code.angularjs.org/1.4.12/angular.js"
            data-require="angular.js@1.4.x">
    </script>
</head>
  
<body ng-app="plunker" 
      ng-controller="MainCtrl">
    <my-directive username="GeeksforGeeks"></my-directive>
  
    <script>
        var app = angular.module('plunker', []);
        app.controller('MainCtrl', function ($scope) {
            $scope.GeeksforGeeks = 'GeeksforGeeks';
        });
  
        app.directive('myDirective', function () {
            return {
                restrict: 'E',
                scope: {
                    username: '='
                },
                link: link,
                template: '<div ng-click="click()">Click Here</div>'
            };
            function link(scope, elem, others) {
                scope.click = function () {
                    console.log('on click', scope.username);
                }
            }
        });
    </script>
</body>
  
</html>


Output:

 

Compile: The Compile function is used to change the DOM before it is rendered, i.e., Compile function compiles your directives in Angular JS. It also produces a link function (that will take care of the linking for us). Additionally, any methods that must be shared across all instances of this directive, should be placed here. The Angular stage that generates the template function is known as the compilation phase. The linking in angular is the name of this template function.

The service $compile is in charge of linking the view to the proper scope and compiling the view. It gathers all the directives by navigating the DOM. There is a linking function as a result.

Syntax:

function compile(tElement, tAttrs, transclude) { 
    ...
}

Example: This example describes the basic usage of the Compile in Angular JS.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <style>
        b {
            color: green;
        }
    </style>
    <script src=
    </script>
</head>
  
<body ng-app="myModule">
    <div ng-controller="myController">
        <textarea ng-model="txt"></textarea>
        <input type="button" 
               value="submit" 
               ng-click="submit()" />
        <div id="display"></div>
    </div>
    <script>
        angular
            .module("myModule", [])
            .controller("myController", ['$scope', '$compile', 
                function ($scope, $compile) {
                $scope.txt = 
                "<b>GeeksforGeeks: Learning portal for Geeks</br></b>";
                $scope.submit = function () {
                    var html = 
                    $compile($scope.txt)($scope);
                    angular.element(document.getElementById("display"))
                    .append(html);
                }
            }]);
    </script>
</body>
  
</html>


Output:

 

Difference between link & compile in Angular JS:

Link

Compile

The Link can be utilized to customize & manipulate the DOM elements with help of Custom Directives.

Compile is utilized to compile the HTML string or the DOM element & convert it into the template, & correspondingly produce the template function, which is used to link the scope and the template together

You attach the data ($scope) to the linking function during the linking step, and it should then return the linked HTML.

The actual compilation of your directive by Angular occurs during this stage.

It creates a live view by fusing the directives and a scope.

It gathers all of the directives by navigating the DOM. There is a linking function as a result.

Link function in Angular Js operates on instances. 

Compile function in Angular Js operates on the template.

The function where you want to modify the link is this one.

The Angular stage that returns the template function is known as the compilation phase.

Create data binding, add event listeners, and alter the resulting DOM element instances through programming.

When using ng-repeat, you can programmatically change the DOM template to apply features to multiple copies of a directive.

Link is applied when an event handler has to be attached.

When we need to change the directive template, we use this.

This function is applied for DOM manipulation.

This function is used to insert a new expression or a new directive inside of another directive.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads