将click事件绑定到AngularJS指令内的子元素 [英] Binding click event to child element inside directive of AngularJS
问题描述
我有以下指示.
(function () {
'use strict';
angular.module('ap.App')
.directive('clearCancelFinishButtonsHtml', function () {
return {
scope: {
clearFunction: '='
},
replace: true,
templateUrl: 'directives/clearCancelFinishButtons.html',
link: function (scope, el, attrs) {
var clear= angular.element(el.find('button.clear'));
console.log(el.find('.clear'));
clear.bind("click", function () {
alert("here");
});
}
}
});
})();
它指向html文件,如下所示
and it is pointing to the html file as follows
<div class="row pull-right">
<div class="col-lg-12 col-md-12 col-sm-12">
<button type="button" class="custom-default clear">CLEAR</button>
<button type="button" class="custom-danger">CANCEL</button>
<button type="button" class="custom-info" ng-click="ap.save()">FINISH</button>
</div>
</div>
我想做的就是在指令中的 clear
类中抓住按钮,并将click事件传递给它.出于某种原因,元素的click事件似乎可以正常工作,但是我无法控制子元素的绑定.任何帮助将不胜感激.
What I wanted to do is grab the button with clear
class inside the directive and pass a click event to it. For some reason, click event to element itself seems to work but I couldn't get the hold of child element to bind it. Any help will be much appreciated.
PS.我正在使用指令< clear-cancel-finish-buttons-html id ="{{$ id}}""clear-function ="'resetConfigurationPageInputs'></clear-cancel-finish-buttons-html>
PS.
I am using the directive as
<clear-cancel-finish-buttons-html id="{{$id}}" clear-function="'resetConfigurationPageInputs'">
</clear-cancel-finish-buttons-html>
更新----------
UPDATE----------
我希望发生这种情况,因为我希望能够从指令声明本身中动态添加和删除函数.
I wanted this to happen as I want to be able to dynamically add and remove function from the directive declaration itself.
推荐答案
谢谢大家的尝试,
我使用以下代码进行操作.
I got it working with the following code.
(function () {
'use strict';
angular.module('ap.App')
.directive('clearCancelFinishButtonsHtml', function () {
return {
scope: {
clearFunction: '='
},
replace: true,
templateUrl: 'directives/clearCancelFinishButtons.html',
link: function (scope, el, attrs) {
var buttons=el.find('button');
angular.forEach(buttons, function(button){
var buttonEl=angular.element(button);
if(buttonEl.hasClass("clear")){
buttonEl.bind("click", function () {
alert("here");
});
}
})
}
}
});
})();
快乐编码;)
这篇关于将click事件绑定到AngularJS指令内的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!