AngularJS - Adding an onClick event to a Button via a Directive

Problem

I'd like to add a click event to an element with a directive. The important part is to not define the button or hyperlink or whatever in the directive but only the onClick attribute and the function, that is called.

So the HTML looks something like this:

<button my-dir type="button" class="btn btn-primary">test</button>

My directive looks like this:

.directive('myDir', function(){
   return {
       restrict: 'A',
       scope: true,
       link: function(scope, element, attrs) {

           scope.functionToBeCalled = function(){
               console.log("It worked!");
           }
       }
   }
})

I have tried adding a "click" like this:

element.bind('click',scope.functionToBeCalled());

Unfortunately this calls the function once when link is called, but not when the button is clicked. I think I have to use compile rather than link and move the functionToBeCalled into the function returned by compile. Sadly I don't know how to accomplish that.

Thanks for your help!

Problem courtesy of: olu

Solution

It should be like this:

.directive('myDir', function () {
    return {
        restrict: 'A',
        scope: true,
        link: function (scope, element, attrs) {

            function functionToBeCalled () {
                console.log("It worked!");
            }

            element.on('click', functionToBeCalled);
        }
    };
});

The line of yours element.bind('click', scope.functionToBeCalled()) is not correct, because you want to pass function reference, not the result of its immediate invocation (what happens if you put () after function name).

Solution courtesy of: dfsq

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.