Umer Farooq Umer Farooq - 1 year ago 149
Javascript Question

Directive is being called only once

I have created a custom directive that goes inside my input field. The purpose of this directive is to analyse the values/data inside the Inputfield.

This directive is supposed to be called everytime the inputField is given focus/cursor.

However the problem is, my custom directive is only being called once. I am not sure why isn't it getting called every time the input field is focused.

What am I doing wrong here?

I am new to Angular so I am sure there is some important detail that I have missed somewhere.

Here is the plunker.

Answer Source

That's expected behaviour, the link function is only called once for any given instance of a directive. Since you're interested in the focus event, I added an event listener to the element the directive is applied to:

var mainApp = angular.module("myapp", ['ngMaterial']);

mainApp.directive("myDirective", function($log) {
    return {
        restrict : 'A',
        require : "ngModel",
        scope   : {
            myDirective : "="
        link    : function(scope, element, attrs, ngModel) {
          element.on('focus', doSomething);

          function doSomething() {
            $log.log("value is:", scope.myDirective);
            if (ngModel.$isEmpty() && scope.myDirective && scope.myDirective.length > 0) {


Since you also mentioned 'cursor', you might be interested in the mouseover event as well. It's as simple as adding another event listener:

element.on('mouseover', doSomething)

Note: I added an additional check for scope.myDirective to avoid the javascript errors on reading length of undefined.

At OP's request:

I don't know if jqLite supports all of these, but for a list of all DOM events you should check this page, your're probably most interested in the focus-, keyboard- & mouse events.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download