我有一个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);
});
}
}
});
而在我的HTML中,我这样使用它:
<sample id="myElement">
<item>1</item>
<item>2</item>
</sample>
将被渲染为:
<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>
我希望能够通过jQuery手动触发事件,并进行监听:
$("#myElement").on("myEvent.sample", function (e, something) {
alert("click: " + something);
});
我希望每次单击链接时都触发此事件。 如果我在
sample
指令上将replace
属性设置为false
,它就可以工作。我猜这是因为在触发事件的时候,元素sample
已经不存在了,因此它将被内部模板替换。
那么,我该如何实现这一点呢?
按照下面答案中的建议执行此操作将无法实现我的目的:$($element).trigger("myEvent.sample", [something]);