Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  26] [ 5]  / answers: 1 / hits: 19105  / 10 Years ago, thu, september 18, 2014, 12:00:00

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!


More From » angularjs

 Answers
29

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


[#69412] Tuesday, September 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annalieset

Total Points: 733
Total Questions: 92
Total Answers: 109

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
;