我在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',require: "^sample",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,则它可以正常工作.我想这是因为在事件被触发的时刻,元素样本不再存在,因此它将被内部模板替换.
那么,我该如何做到这一点?
如下面的答案所示,这样做不会达到我的目的:
$($element).trigger("myEvent.sample",[something]);