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!
For a single btn, it's ok to use ng-click or onclick in the ng-app . There is no difference between the two functions. For effective team work, you,d better to have an account with each other. In Angular apps, ng-click is recommended.
Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.
We can bind a JavaScript function to a div using the onclick event handler in the HTML or attaching the event handler in JavaScript. Let us refer to the following code in which we attach the event handler to a div element. The div element does not accept any click events by default.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With