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
<div ng-app='app' ng-controller='mainCtrl'>
<div app-click="">
<div ng-repeat="json in myJson">
<li data-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 div
list 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);
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<div ng-app='app' ng-controller='mainCtrl'>
<div app-click="">
<div ng-repeat="json in myJson">
<li>{{json}}</li>
</div>
</div>
</div>
Post a Comment for "Get The Index Of The Click Element"