AngularJS-将点击事件绑定到指令元素的子元素
AngularJS - Bind click event to children of directive element
我又开始使用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();
});
}
};
我想给第一个子div分配一个点击事件(在这里我检查CSS),并根据"数据url"执行某些任务。我真的不想在HTML中给子div添加ng-click
指令。有人能告诉我如何在子div中添加点击事件吗?
非常感谢
如果使用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
}
});
})
}
相关文章:
- 指令的模板必须只有一个根元素:With restrict E&替换true
- 在元素指令上添加 css
- replace:true 如何与元素指令一起使用
- 防损层,从角度元素指令传递属性指令
- 角度:在元素指令上添加属性指令
- 如何在 angularjs 中验证元素指令
- 删除对象时执行元素指令动画的角度方式
- 从元素指令中的路由提供程序获取参数
- 基于会话服务的隐藏/显示元素指令-AngularJS
- AngularJS:从控制器中访问元素指令的属性
- 自定义元素指令和属性
- 如何在元素指令上使用ng-if来有条件地调用模块
- 将属性指令传递给元素指令
- 如何在AngularJS中以编程方式计算HTML元素(指令)的属性名
- 正在包装集合指令中元素指令的模板
- 无法正确使用元素指令
- Angularjs嵌套元素指令
- 使用 AngularJS 在选择元素指令中触发消息“onfocusleave”的“console.log”
- Angular自定义元素指令没有显示在屏幕上
- 带ng-init的AngularJS元素指令在视图渲染之前运行