Angular ng-click 事件委托 [英] Angular ng-click event delegation
问题描述
因此,如果我有一个包含 100 个 li 的 ul,每个 li 中应该有 ng-clicks 还是有一种方法可以将事件绑定到 ul 并将其委托给 li 的类型,就像 jquery 所做的那样?这会更好还是更糟?我们有 100 个事件,还是最后只有一个事件?
So if i have a ul with 100 li's should there be ng-clicks in each li or is there a way to bind the event to the ul and delegate it to the li's kind of what jquery does? Would this be better or worse? Are we having 100 events or is it just one event in the end?
推荐答案
似乎 angular 不使用中继器进行事件委托.有人在 github 上打开了一个问题.争论的焦点是它是否真的能带来更好的性能.
It seems angular doesn't do event delegation with repeaters. Someone opened an issue on github about it. The argument is if it actually leads to better performance.
可能有一种解决方法,但它需要 jQuery.它包括创建一个用于父元素的特殊指令,并在其 dom 节点上注册侦听器.
There might be a workaround but it would require jQuery. It consists of creating a special directive to be used on a parent element and register the listener on its dom node.
这是一个例子,它传递了一个函数名,当一个子节点被点击时被调用,还传递了一个选择器来帮助识别要侦听的子节点.由于 angular 的 jquery 实现只为我们提供了 bind
方法 - 该方法仅限于将事件侦听器注册到实际元素 - 我们需要加载 jQuery 才能访问 on
或委托
方法.
Here's an example, that is passed a function name to be called when a children node is clicked, and is also passed a selector to help identify which children nodes to listen to.
Since angular's jquery implementation only gives us the bind
method - which is limited to registering event listeners to the actual element - we need to load jQuery to have access to either the on
or delegate
method.
HTML
<ul click-children='fun' selector='li'>
<li ng-repeat="s in ss" data-index="{{$index}}">{{s}}</li>
</ul>
定义的函数在控制器中定义,它期望传递一个索引
The function defined is defined in the controller and it expects to be passed an index
$scope.fun = function(index){
console.log('hi from controller', index, $scope.ss[index]);
};
该指令使用 $parse
将表达式转换为将从事件侦听器调用的函数.
The directive uses $parse
to convert an expression into a function that will be called from the event listener.
app.directive('clickChildren', function($parse){
return {
restrict: 'A',
link: function(scope, element, attrs){
var selector = attrs.selector;
var fun = $parse(attrs.clickChildren);
element.on('click', selector, function(e){
// no need to create a jQuery object to get the attribute
var idx = e.target.getAttribute('data-index');
fun(scope)(idx);
});
}
};
});
Plunker:http://plnkr.co/edit/yWCLvRSLCeshuw4j58JV?p=preview
注意:可以使用隔离作用域{fun: '&'}
将函数委托给指令,这值得一看,但这会增加复杂性.
Note: Functions can be delegated to directives using isolate scopes {fun: '&'}
, which is worth a look, but this increases complexity.
这篇关于Angular ng-click 事件委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!