Oliver Watkins
Oliver Watkins

Reputation: 13509

How to get the event source from calling element

I have an event listener in a list item :

        <li class="item" ng-click="click($event)">
            <a href="#/home">Home</a>
        </li>

In my controller I have a click handler :

 $scope.click = function($event) {      
        t2 = $($event.target.parentElement);
        t2.addClass('clicked');
}

However, sometimes my $event.target is the list element, and sometimes it is the anchor element. This is because of where I click, sometimes it is on the a element but not on the list. Is there a way of getting from the event object the element that called the function?

Upvotes: 0

Views: 136

Answers (2)

Kyle
Kyle

Reputation: 5557

Don't mess with the DOM inside controllers. Use directives instead.

According to Angular JS Documentation

Do not use controllers to:

  • Manipulate DOM — Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.
$scope.selectedId = null;

$scope.clickFn = function(e) {
    $scope.selectedId = e.currentTarget;
}

HTML:

<li ng-class="{ 'clicked-class-name' : selectedId === 'someId' }" id="someId" ng-click="clickFn($event)">

Upvotes: 1

Hmahwish
Hmahwish

Reputation: 2232

Use $event.currentTarget

 $scope.click = function($event) {      
    t2 = $($event.currentTarget.parentElement);
    t2.addClass('clicked');

}

Upvotes: 1

Related Questions