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

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

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!

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

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).

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