Red
Red

Reputation: 7299

Get element ng-class AngularJS

Ive have an element like this:

<div class="someclasses" ng-class="{'new-class': function()}">

If using ng-click we can get the element by passing the $event. Like so:

<div class="someClasses" ng-click="function($event)">

Then get the target element like so:

$scope.function = function($event) {
    console.log($event.currentTarget); // Logs the current target element
}

However, ng-class does not support event object $event being passed as a parameter.

So my question is, how can I get the target element where ng-class is assigned too?

I cannot use the angular.element('classname') selector, as the expression inside the function looks for a classname which is added dynamicly, on the element where the ng-class is assigned too.

Upvotes: 1

Views: 1670

Answers (1)

31piy
31piy

Reputation: 23859

In the simplest terms, this is not possible. You will need to write a custom directive to do that, as specified in this thread.

Alternatively, if you have the div under an ng-repeat or so, you can manually pass some identifier to your function which will help it in finding the correct info.

<div ng-repeat="item in data track by $index">
  <div class="someclasses" ng-class="{'new-class': classFunc($index)}">
  ...
</div>

This way, the index of the item can be accessed by classFunc and it can find the info in data accordingly.

Upvotes: 1

Related Questions