Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs ng-click $event passes child element as target

For each td element in a table I have an attached ng-click. Here is the (simplified) html for each table cell:

<td ng-click="cellClicked($event)">
    <span ng-if="!cellEdit">{{event.eventName}}</span>
    <input type="text" ng-if="cellEdit" ng-model="event.eventName">
</td>

And my (simplified) ng-click function:

scope.cellClicked = function (event) {
  rowScope.cellEdit = true
  angular.element(event.target).find('input').focus()
}

Its my goal to:

  1. User clicks a table cell
  2. Cell changes to "edit mode"
  3. Give focus to the input element located inside the td.

Right now this is working as long as the user clicks inside the td element but not on the span element:

console.log(angular.element(event.target)) #--> [td...] (as desired)

However if the user clicks on the span element within the td:

console.log(angular.element(event.target)) #--> [span...]

In this use case assigning focus does not work. I was hoping to access the parent element of the span doing something like:

angular.element(event.target.closest('td'))

or

angular.element(event.target.parentNode)

But it appears when an element gets passed through via $event and accessed there is no parent context.

How can I either:

  • Prevent clicking the span element firing the td's ng-click
  • On click of span element pass through it's html parent
like image 722
Cumulo Nimbus Avatar asked Apr 02 '15 19:04

Cumulo Nimbus


2 Answers

Changing:

angular.element(event.target)

to:

angular.element(event.currentTarget)

fixed my issue.

It seems to me using event.currentTarget is preferred to event.target in the majority of usage cases.

like image 150
Cumulo Nimbus Avatar answered Oct 03 '22 02:10

Cumulo Nimbus


event.target.closest('td') won't work because event.target is a DOM element and it doesn't have method closest. You need to create a jQuery object to use this method.

Try to find closest td like this:

angular.element(event.target).closest('td')
like image 34
dfsq Avatar answered Oct 03 '22 01:10

dfsq