如何在 AngularJs 服务中创建自定义事件 [英] How do I create a custom event in an AngularJs service

查看:23
本文介绍了如何在 AngularJs 服务中创建自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个 AngularJs 项目.我有一项服务,可以设置和删除某些按钮上的事件.此服务由另一个服务使用,我不想直接与按钮交互.但是,我希望通过第一个服务过滤按钮单击事件并在第二个服务中处理.因为我不希望第二个服务知道这些按钮,所以我想我需要在第一个服务中创建一个自定义事件.如何创建自定义事件并在单击按钮时触发它?

I am working on an AngularJs project. I have a service which sets and removes events on some buttons. This service is utilized by another service which I do not want to interact directly with the buttons. However I would like a button click event to be filtered up through the first service and handled in the second one. Since I don't want the second service to be aware of the buttons, I figure I will need to create a custom event in the first service. How can I create a custom event and fire it when a button is clicked?

提前致谢.

推荐答案

如果您想在服务/指令之间发送事件,请使用 broadcast:

If you want to send an event between services/directives use broadcast:

$rootScope.$broadcast('buttonPressedEvent');

并像这样收到它:

$rootScope.$on('buttonPressedEvent', function () {
             //do stuff
        })

这篇关于如何在 AngularJs 服务中创建自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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