根据 jm- 的示例,我编写了该指令的更简洁灵活的版本。以为我会分享。归功于 jm- ;)
我的版本尝试将函数名称调用为 $scope[ fn ]( e, data ),或者正常失败。
它从被点击的元素中传递一个可选的 json 对象。这允许您使用 Angular 表达式并将大量属性传递给被调用的方法。
HTML
<ul delegate-clicks="handleMenu" delegate-selector="a">
<li ng-repeat="link in links">
<a href="#" data-ng-json='{ "linkId": {{link.id}} }'>{{link.title}}</a>
</li>
</ul>
Javascript
控制器方法
$scope.handleMenu = function($event, data) {
$event.preventDefault();
$scope.activeLinkId = data.linkId;
console.log('handleMenu', data, $scope);
}
指令构造函数
// The delegateClicks directive delegates click events to the selector provided in the delegate-selector attribute.
// It will try to call the function provided in the delegate-clicks attribute.
// Optionally, the target element can assign a data-ng-json attribute which represents a json object to pass into the function being called.
// Example json attribute: <li data-ng-json='{"key":"{{scopeValue}}" }'></li>
// Use case: Delegate click events within ng-repeater directives.
app.directive('delegateClicks', function(){
return function($scope, element, attrs) {
var fn = attrs.delegateClicks;
element.on('click', attrs.delegateSelector, function(e){
var data = angular.fromJson( angular.element( e.target ).data('ngJson') || undefined );
if( typeof $scope[ fn ] == "function" ) $scope[ fn ]( e, data );
});
};
});
如果有人愿意贡献,我很乐意听取反馈。
我没有测试 handleMenu 方法,因为我从更复杂的应用程序中提取了它。