问题
Need to bind an event to directive's children which is prepared with ng-repeat in templateUrl.
I am trying to bind the event in link
function but the children are not yet prepared.
Here is the plunker.
Here I want to bind click
event on li
tag which are prepared with ng-repeat.But by the time, the link
is executed, the li
elements are not yet prepared.

Can somebody please help.
回答1:
I've resolved the same problem with the angular $timeout
link: function (scope, element) {
$timeout(function () {
element.on('click', '#Id', function () {
console.log('inside event handler of the first child)
})
})
}
Try this by injecting $timeout in your directive
回答2:
Solution #1 using angular ng-click directive (plunker)
<button ng-click="showValuePopup = !showValuePopup;">Click</button>
<div ng-show="showValuePopup">
<ul>
<li ng-click="$parent.showValuePopup = false;" ng-repeat="option in options" value="{{ option.value }}"
symbol="{{ option.symbol }}">{{ option.text }}
</li>
</ul>
</div>
Solution #2 use additional directive with timeout that fire event after ng-repeat last element loads (plunker)
app.directive('onLastRepeat', function () {
return function (scope, element, attrs) {
if (scope.$last) setTimeout(function () {
debugger;
scope.$emit('onRepeatLast', element, attrs);
}, 1);
};
});
and listen for this event in link function:
$scope.$on('onRepeatLast', function(scope, element, attrs){
// make what you want
valuePopup.find('li').on('click',function(){
valuePopup.hide();
});
valuePopup.find('keydown').on('click',function(){
valuePopup.hide();
});
});
回答3:
maybe it will help you
app.directive('gtmsCycleButton', function () {
return{
restrict: 'EA',
link: function (scope, el, attrs) {
scope.$watch(attrs.options, function(newVal, oldVal) {
if (newVal === oldVal) return;
var btn = $(el).find('.v-btn'),
valuePopup = $(el).find('.v-value-popup');
btn.on('click', function() {
console.log('Button Clicked');
valuePopup.toggle().focus();
});
valuePopup.find('li').on('click', function() {
valuePopup.hide();
});
valuePopup.find('keydown').on('click', function() {
valuePopup.hide();
});
});
},
templateUrl: 'temp1'
}
});
来源:https://stackoverflow.com/questions/27656721/bind-event-to-child-element-of-directive-in-link-function