I have a directive in AngularJS:
module = angular.module("demoApp", [], null); module.directive('sample', function () { return { restrict: "E", transclude: true, replace: true, template: "<div ng-transclude></div>", controller: function ($scope, $element) { this.act = function (something) { //problematic line HERE $element.trigger("myEvent.sample", [something]); }; } }; }) .directive('item', function () { return { restrict: "E", require: "^sample", transclude: true, replace: true, template: "<a ng-transclude style='display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;'></a>", link: function (scope, element, attributes, parentController) { element.on("click", function () { parentController.act(this.innerText); }); } } });
And in my HTML, I use it this way:
<sample id="myElement"> <item>1</item> <item>2</item> </sample>
What will be displayed as:
<div ng-transclude="" id="myElement"> <a ng-transclude="" style="display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;;display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;" class="ng-scope"><span class="ng-scope">1</span></a> <a ng-transclude="" style="display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;;display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;" class="ng-scope"><span class="ng-scope">2</span></a> </div>
I want to be able to listen to events triggered manually through jQuery:
$("#myElement").on("myEvent.sample", function (e, something) { alert("click: " + something); });
I want this event to fire whenever the link is clicked.
If I set the replace property to false in the sample directive, it works. I assume this is because the moment the event is fired, the sample element no longer exists, and as such it will be replaced by an internal template.
So how to do this?
Doing this as suggested in the answer below will not achieve my goal:
$($element).trigger("myEvent.sample", [something]);