How do you check if & variable is set in directive

All we need is an easy explanation of the problem, so here it is.

In a directive, where you set a method callback through an arg, say:

<my-directive callback='showAlert()' />

You can retrieve the variable through the scope setting in the return:

scope: {
    callback: "&callback"
}

If the callback is not set, eg:

<my-directive />

The value of $scope.callback is still:

$scope.callback():function (locals) {
    return parentGet(scope, locals);
}

Is there a good way to check that the callback was not set?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

One way i can think off is to check the attribute parameter for the directive name like

link: function (scope, elm, attrs) {

   if(attrs.callback) {
       //this attribute has been defined.
   }

}

Method 2

You can use &? insteand of &. It will make $scope.callback equal to undefined if it is not provided.

Method 3

Because parameters that are passed to the directive will reside on the directive’s scope, I prefer to check for type. Even thought it’s defined as expression in the scope configuration:

scope: { callback: '&attrName' },
link: function(scope, ...){
    if (typeof scope.callback === 'function') {
        // do my stuff
    }
}

that way I always sure I’m getting what I expect.

Method 4

this approach worked for me:

scope: {
  callback: '&callback',
  callbackExists: '@callback'
}

Then using the second parameter in the template:

<div ng-if="callbackExists">…</div>

Method 5

use angular.isUndefined to check callback function

link: function(scope, element, attrs) {
    if (angular.isUndefined(scope.callback)) {
        // do something when callback undefined
        return;
    }
    // do something when callback defined
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply