你可以在自定义指令属性的使用角度事件监听器? [英] Can you use an angular event listener in a custom directive attribute?

查看:172
本文介绍了你可以在自定义指令属性的使用角度事件监听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在普通的HTML,我们可以直接添加监听器在HTML元素例如事件。

In normal HTML we can directly add listeners to events on HTML elements e.g.

<button onclick="doMyMethod()">Click me</button>

我有发射事件,dataLoaded的自定义指令。我想一个处​​理程序声明添加到开始元素来处理该事件。但是我不知道如何做到这一点。

I have a custom directive which emits an event, "dataLoaded". I'd like to declaratively add a handler to the element to deal with that event. However I'm not sure how to do this

我在这里做了一个方法,但我喜欢做的事是这样的:

I'm making up a methodology here but I'd like to do something like:

<my-element ng-on="'dataLoaded', doMyMethod" ></my-element>

的(不良)替代

另一种方法是使用 $范围。$上(dataLoaded,doMyMethod())控制器,但我会preFER宣布这对元件本身。

The (undesirable) alternative

The alternative is to use $scope.$on("dataLoaded", doMyMethod()) in the controller but I would prefer to declare this on the element itself.

这可能吗?

推荐答案

而不是用在这里的事件,你应该通过你的方法到像这样的指令:

Instead of using an event here, you should pass your method into the directive like so:

angular.module('myApp').directive('myElement', function() {
    return {
        scope: {
           // way to bind method to your directive's scope
           dataLoaded: '&'
        },
        link: function(scope, element) {
            ...
            // instead of triggering data loaded, call method bound to scope
            scope.dataLoaded();
            ...
        }
});

您的HTML:

<my-element data-loaded="doMyMethod"></my-element>

这篇关于你可以在自定义指令属性的使用角度事件监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆