Bind events on AngularJS element directives using jQuery
Please find below the fiddle
fiddle
Trigger is a jquery function which will work on proper handler.
$(element).trigger("myEvent.sample");
Hope this helps
Here's updated fiddle: http://jsfiddle.net/3u3zh/1/
There are several points worth noticing:
Because of the way angular transforms DOM, I would advice attaching all your custom listeners on body and then filter them by event target.
$('body').on('myEvent.sample', 'target-selector-expr', handler)
does exactly that. For example, if you use custom event listeners onngRepeat
ed elements, your handlers would not be executed because those elements would not exist at the time of trying to attach events to them.It seems that angular's jqLite implementation is somewhat lacking in features when triggering events. Therefore I wrapped
sample
's element in jQuery ($($element)
) because otherwise the additional data would not get to the handler.
Final template:
<div ng-app="myApp">
<sample id="myElement"><item>1</item><item>2</item></sample>
</div>
Js:
var myApp=angular.module('myApp',[]);
myApp.directive('sample', function () {
return {
restrict: "E",
replace: true,
transclude: true,
template: "<div ng-transclude></div>",
controller: function ($scope, $element) {
this.act = function (something) {
$($element).trigger("myEvent.sample", [something]);
};
}
};
})
.directive('item', function () {
return {
restrict: "E",
require: "^sample",
transclude: true,
template: "<a ng-transclude></a>",
link: function (scope, element, attributes, parentController) {
element.on("click", function(e) {
parentController.act(this.innerHTML);
});
}
}
})
$(document).ready(function(){
$("body").on("myEvent.sample", '#myElement', function (e, something) {
alert('clicked: ' + something);
});
});