3

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.

2 Answers 2

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());
            });
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Yes, I want to add a click handler to your my directive
@Avraam I updated the code to hide the element on click

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.