Skip to content Skip to sidebar Skip to footer

Get The Index Of The Click Element

I am trying to get the index of the clicked element but I keep getting -1 in the console. I am using Array.prototype to get the indexOf from the nodelist HTML:

Solution 1:

Other option is to set the index

<divng-app='app'ng-controller='mainCtrl'><divapp-click=""><divng-repeat="json in myJson"><lidata-index="{{$index}}">{{json}}</li></div></div></div>

and read it in the click

e.target.dataset.index

Solution 2:

e.target return li element,$element.children() return divlist not li try this code:

var index = Array.prototype.indexOf.call($element.find("li"), e.target);

angular.module('app', []).controller('mainCtrl', function($scope) {
  $scope.myJson = ["mayank1", "mayank2", "mayank3", "mayank4", "mayank5", "mayank6", "mayank7", "mayank8", "mayank9"]
})

.directive('appClick', function() {
  return {
    restrict: 'A',
    scope: true,
    controller: function($scope, $element) {
      $element.bind("click",function(e){
      		var index = Array.prototype.indexOf.call($element.find("li"), e.target);
          console.log(index);
      });
    }
  }
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script><divng-app='app'ng-controller='mainCtrl'><divapp-click=""><divng-repeat="json in myJson"><li>{{json}}</li></div></div></div>

Post a Comment for "Get The Index Of The Click Element"