I am trying to understand a bit further how directives work, so I wrote this simple directive:
Avraam.directive('whoami',function(){
return{
restrict:'A',
template:"<label id='avraam'>Avraam</label>",
link:function(scope, element, attrs) {
var avraam = $(element).find('#avraam');
$(avraam).hide();
}
}
});
People support that the DOM manipulation should be done inside the directive, so I want to ask how can I create an ng-click event handler inside the directive, when the user clicks on the element the elemented will be hidded.
If all that is needed is to hide the element, it can be achieved via ngClick and ngHide in the template...
Avraam.directive('whoami',function(){
return{
restrict:'A',
scope: {},
template:"<label ng-click='hidden = true' ng-hide='hidden' id='avraam'>Avraam</label>"
}
});
JSFiddle
If you need a click handler to do some other work, you can use ngClick in the template to call a method on the scope...
Avraam.directive('whoami',function(){
return{
restrict:'A',
template:"<label ng-click='doSomething()' id='avraam'>Avraam</label>",
controller: function ($scope, $element) {
$scope.doSomething = function () {
// do work with $element here
alert($element.text());
};
}
}
});
JSFiddle
And here's a variation using a click handler...
Avraam.directive('whoami',function(){
return{
restrict:'A',
template:"<label id='avraam'>Avraam</label>",
link: function (scope, element) {
element.on("click", function () {
alert(element.text());
});
}
}
});
ng-click is a directive, it sounds like you want to add a click handler to your own directive. To do this you would simply add the handler to your element in the link method:
Avraam.directive('whoami',function(){
return{
restrict:'A',
template:"<label id='avraam'>Avraam</label>",
link:function(scope, element, attrs) {
element.bind("click", function(){
$(this).hide();
});
}
}
});
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