Search code examples
javascriptangularjsangularjs-directivecallbackdefault

AngularJS Directives - specify defaults for callbacks


I have a directive that takes a few methods as callbacks. All of them require attributes to work.

scope: {
    onEventOne: '&?',
    onEventTwo: '&?'
}

function someWork() {
    onEventOne()(myVar);
    onEventTwo()(myOtherVar);
}

My problem is when I don't have some of those callbacks defined, as they are not all required.

<div>
    <myDirective on-event-one="customHandler"></myDirective>
</div>

In the code above, when calling onEventOne()(myVar); everuthing works, but when calling onEventTwo()(myOtherVar); I get TypeError: undefined is not a function. I tried using the link function to set a blank function as default,

function linkFunction(scope, element, attrs) {
    if (!attrs.onEventOne) {scope.onEventOne = scope.blankHandler;}
    if (!attrs.onEventTwo) {scope.onEventTwo = scope.blankHandler;}
}

but that causes the the default function to be called while still throwing TypeError: undefined is not a function.

How do I set these default functions?


Solution

  • The usage of your functions implies that blankHandler must return one more "blank" function (angular.noop is convenient here). This is what I would do in link function in your case:

    var blankHandler = function() {
        return angular.noop;
    };
    
    if (!attrs.onEventOne) {scope.onEventOne = blankHandler;}
    if (!attrs.onEventTwo) {scope.onEventTwo = blankHandler;}
    
    scope.onEventOne()(myVar);
    scope.onEventTwo()(myOtherVar);