How to check if a method argument of a directive is specified in AngularJS? How to check if a method argument of a directive is specified in AngularJS? angularjs angularjs

How to check if a method argument of a directive is specified in AngularJS?


Using '&?' returns undefined if the attribute has not been set.

'&' = callback function is defined always.

'&?' = callback function is defined only when attribute is defined in html template.

bindToController: {    callback: '&?'},controller: function() {    if (this.callback === undefined) {        // attribute "callback" was not defined    }}

Note: Works in Angular 1.4.8. I'm not sure if it works in older versions.


Looking at angularjs source code, I see this:

case '&':    parentGet = $parse(attrs[attrName]);    isolateScope[scopeName] = function(locals) {         return parentGet(scope, locals);    };    break;

The parentGet is the bound function expression. Unfortunately, this is a local variable which is only available to the function assigned to isolateScope[scopeName] via closure.

Instead of trying to find a way to get that variable, a simple solution is just to check the attrs. Try:

link: function(scope,elem,attrs) {      scope.hasCallback = function() {        return angular.isDefined(attrs.callback);      }    }

DEMO