我正在尝试获取被点击元素的索引,但我一直在控制台中获得-1
。我正在使用Array.prototype
从indexOf
nodelist
HTML:
<div ng-app='app' ng-controller='mainCtrl'>
<div app-click="">
<div ng-repeat="json in myJson">
<li>{{json}}</li>
</div>
</div>
</div>
JS:
.directive('appClick', function() {
return {
restrict: 'A',
scope: true,
controller: function($scope, $element) {
$element.bind("click",function(e){
var index = Array.prototype.indexOf.call($element.children(), e.target);
console.log(index);
});
}
}
});
答案 0 :(得分:4)
其他选项是设置索引
<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>
并点击
阅读e.target.dataset.index
答案 1 :(得分:2)
e.target
返回li元素,$ element.children()返回div
列表而不是li
试试这段代码:
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);
});
}
}
});
&#13;
<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>
&#13;