我回到使用AngularJS而我已经忘记了一切。我的html视图中有一个包含自定义指令的div,子DIV有一个ng-repeat
指令,这是我的HTML:
<div class="row" data-custom-directive>
<div class="col-xs-2 main-nav-cell" data-ng-repeat="nav in mainNavigation.topNavi" data-url="{{ nav.link }}">
<div> {{ nav.name }} </div>
<div class="item-counter" data-ng-show="nav.value > 0"> {{ nav.value }} </div>
</div>
</div>
现在在我的自定义指令中,我等待ng-repeat
完成然后我遍历子DIV并执行某些任务(我在这里省略了一些)。
.directive('customDirective', function ($location, $timeout, $rootScope) {
'use strict';
return{
restrict: 'A',
link: function (scope, element) {
$timeout(function () {
var i,
list = angular.element(element),
cssCheck = function () {
for (i = 0; i < list[0].children.length; i++) {
/*
Here I wish to set a click event on the Child DIV
I have tried list.children()[i].click = fn & list.children()[i].bind('click' fn)
but nothing works!
*/
// if the class is there remove it...
if (list.children()[i].classList.contains('is-active')) {
list.children()[i].classList.remove('is-active');
}
// if there is a match add the class...
if ($location.url().indexOf(list[0].children[i].getAttribute('data-url')) > 0) {
console.log('match');
list.children()[i].classList.add('is-active');
}
}
};
$rootScope.$on('$routeChangeSuccess', function () {
cssCheck();
});
// original kickoff
cssCheck();
});
}
};
我想将click事件分配给第一个子div(我检查CSS)并执行某些任务,具体取决于'data-url'我真的不想添加ng-click
指令我的HTML中的孩子。有人可以告诉我如何向孩子div添加点击事件吗?
非常感谢
答案 0 :(得分:3)
如果使用jQuery:
link: function (scope, element) {
$timeout(function () {
element.on('click', ':first', function () {
console.log('inside event handler of the first child)
})
})
}
如果不使用jQuery
link: function (scope, element) {
$timeout(function () {
angular.element(element).on('click', function (evt) {
var isFirstChild = (evt.target.parentElement.children[0] === evt.target);
if (isFirstChild) {
// do the stuff
}
});
})
}