Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  109] [ 1]  / answers: 1 / hits: 5198  / 10 Years ago, tue, may 13, 2014, 12:00:00

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.


More From » jquery

 Answers
1

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());
});
}
}
});

[#45338] Monday, May 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristineterrak

Total Points: 74
Total Questions: 109
Total Answers: 115

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;