使用jQuery绑定AngularJS元素指令上的事件

Mil*_*eri 7 jquery events javascript-events angularjs angularjs-directive

我在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);
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

在我的HTML中,我使用它:

<sample id="myElement">
    <item>1</item>
    <item>2</item>
</sample>
Run Code Online (Sandbox Code Playgroud)

哪个将呈现为:

<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>
Run Code Online (Sandbox Code Playgroud)

我希望能够通过jQuery手动触发事件:

$("#myElement").on("myEvent.sample", function (e, something) {
    alert("click: " + something);
});
Run Code Online (Sandbox Code Playgroud)

我想要在点击链接时触发此事件.

如果我的设置replace属性falsesample指令,它的工作原理.我想这是因为在触发事件的时刻,元素sample不再存在,因此它将被内部模板替换.

那么,我该如何做到这一点?

如下面的答案所示,这样做不会达到我的目的:

$($element).trigger("myEvent.sample", [something]);
Run Code Online (Sandbox Code Playgroud)

Sai*_*Sai 16

请在下面找到小提琴

小提琴

触发器是一个jquery函数,可以在正确的处理程序上运行.

$(element).trigger("myEvent.sample");
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助