Modifying a tag behavior with an angularJs directive

javaScript angularJs directives

Introduction

In this tutorial we will walk through how to modify the behavior of an a tag to be able to achieve two behaviors.

First behavior is opening a modal or alert with a click, and the second one is to navigate to a page when clicked with a cmd/ctrl combination.

With the help of angularJs directive, we will be able to achieve these two behaviors with as little code as possible.

Requirements

we have a table that renders some data. One column contains links to entities that when click will open a modal to give you a summary of that entity, there is a button inside the modal that navigates to the entity.

We need to add a second behavior to these a tags. When clicked in combination with cmd/ctrl it should open the link in a new window, since the data of the table is dynamic we have to build the hrefs dynamically.

Implementation

Let's start by having the a tag open a simple alert modal when clicked

<a ng-click='openAlert()'>hello world</a>

and the function for opening the alert is as follows

function openAlert() {
    alert('hello world');
}

Let's implements the hrefBuilder directive. This directive will modify the href attribute attached to the element that we add the directive to

angular.directive('hrefBuilder', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            // some logic here
            attrs.$set('href', url || '');
        }
    }
})

Let’s walk through the code briefly.

The directive will attach to the element of an a tag.

So the directive need to be restrict to an attribute directive.

We use the link function of the directive to get access to the attributes.

We can add an attribute to the element that the directive is attached too, to hold information to help us build the url.

You can add your own logic to create the href I won’t be going through that.

Now we have to modify the a tag by adding the directive to it like so

<a ng-click='openAlert()' href-builder customAttr='someData'>hello world</a>

One last thing we need to do is differentiate between normal clicks and clicks with cmd/ctrl.

The idea is simple: When the link is clicked, ng-click will fire first, then the href behavior will fire after that. So when the user clicks we need to stop the default behavior of the a tag using:

e.preventDefault();
And when the user click with cmd/ctrl we need to exit ng-click and let the href behavior take precedence

function openAlert() {
    if (e.metaKey || e.ctrlKey) {
        return;
    }
    e.preventDefault();
    alert('hello world');
}

You can checkout a sample project over on GitHub