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

2024-04-21

我在 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]);

请在下面找到小提琴

fiddle http://jsfiddle.net/sb_satchitanand/h49nz/

触发器是一个 jquery 函数,它将在适当的处理程序上工作。

$(element).trigger("myEvent.sample");

希望这可以帮助

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 jQuery 在 AngularJS 元素指令上绑定事件 的相关文章

随机推荐