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!