我在 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);
});
我希望每当单击链接时都会触发此事件。
如果我设置replace
财产给false
on the sample
指令,它有效。我想这是因为在事件被触发时,元素sample
不再存在,因此它将被内部模板取代。
那么,我该如何实现这一点呢?
正如下面答案中所建议的那样,这样做将无法实现我的目的:
$($element).trigger("myEvent.sample", [something]);