Transferring information about service events to a controller in Angular

I am facing an issue with some audio elements in my service that listen for the "ended" event. I am looking for a way to pass this message to an angular controller.

Currently, my service code looks like this:

Audio.addEventListener "ended", (->
      $rootScope.$broadcast("audioEnded")
    ), false

And in my controller, I have the following:

$scope.$on "audioEnded", ->
      console.log("ended scope")

While this solution works, I am exploring alternative methods of communication between services and controllers without relying on $rootScope.

Answer №1

To accomplish your goal, one effective method is to create an event aggregator as a service. This aggregator can be utilized in directives, controllers, or config functions through simple dependency injection.

app.service 'eventAggregator', ->
    handlers: []
    on: (eventName, handler) ->
       #register handler
    emit: (eventName, args...) ->
       #iterate events and call registered handlers

Here's an example of how to use it:

app.controller 'Ctrl', (eventAggregator) ->
    eventAggregator.on 'eventName', ->
        #...
    eventAggregator.emit 'eventName'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

npm not working to install packages from the package.json file in the project

When using my macbook air, I encounter an issue where I can only install npm packages globally with sudo. If I try to install a local package without the -g flag in a specific directory, it results in errors. npm ERR! Error: EACCES, open '/Users/mma ...

Update the text in a personalized dropdown menu when an option is chosen

After spending some time working on a customized dropdown with the use of CSS and Vanilla JavaScript (Plain JS), I encountered an issue while trying to select and update the dropdown text upon clicking an option: window.onload = () => { let [...opt ...

Storing the subscription value retrieved from an API in a global variable

I am trying to find a way to make the data retrieved from an API accessible as a global variable in Typescript. I know that using subscribe() prevents this, so I'm looking for a workaround. Here is the API code: getResultCount(category:any):Obs ...

Having trouble accessing env variables from React Component in Next.js?

I recently set up a Next.js project and included an .env file to store environment variables used in my server.js file. However, I am facing an issue when trying to access these variables from a component. Can anyone provide guidance on how to resolve this ...

Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...

Switch between using a dropdownlist and textbox depending on the selection in another dropdownlist

In the process of developing an application, I have implemented a country dropdown list and a state dropdown list. Here's the scenario: when a user selects a country, the states for that country will populate in the state dropdown list. However, the ...

Click event to focus on AngularJS TinyMCE textarea

My current project utilizes the tinymce text editor in combination with the angularJS framework. I obtained the directive from here and successfully integrated the editor using the provided example on GitHub! Initially, everything was working smoothly wit ...

Waiting for a promise to be returned in AngularJS

There are functions in my AngularJS app that look like this: function createDefaultRequest() { var paramServiceId = currentUser.serviceId; var paramStatuses = myRequestService.getStatuses(); var paramSubServices = []; paramSubServices ...

Having trouble with finding the correct object in an array of objects using indexOf and splice()?

Here is an example of an array of objects: "followers": [ { "id": "1be87842-2f7f-4e3b-8fde-9a998feb3a01", "bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece", "user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda", ...

Issue with Bootstrap.js causing mobile menu to not expand when toggled in Rails app

Despite adding the .toggled class, my hamburger menu is not expanding when I click on the mobile menu. I've tried adjusting the order of the required javascript commands, but it doesn't seem to be working as expected. Here are the steps I'v ...

Is there a way for me to make my Note element automatically update whenever I modify its text content?

Feeling a bit stuck with my project, especially this part. I'm currently using React to develop a notes application, and I'm having trouble updating the note when changing the text within the modal popup. The commented sections are where I need h ...

Retrieving information from MongoDB for a specific ObjectID associated with the current authenticated user

Having two collections in my MongoDB structured as follows: Data User: id: ObjectId ("5fb39e3d11eaad3e30cfb1b0") userName: "Tobias" password: "yyy" id: ObjectId ("5fb3c83fb774ff3340482250") userName: "Thor&qu ...

Encountering the issue of "TypeError: Cannot read property 'file' of undefined" when trying to upload a video with Multer

The objective is to select a video file from the desktop and upload it to the platform. The uploaded video file will then be automatically posted to a specified Youtube channel using GCD. An error message I encountered is:"react-dom.development.js:40 ...

Surprisingly stumbled into the 'restricted' directory while switching the current directory to a temporary folder

I've encountered a strange issue while attempting to create and switch the working directory to a temporary folder using Node.js. Check out the code snippet below: var path = require('path') var fse = require('fs-extra') var TEST ...

Having trouble troubleshooting the jQuery button

When I click this button, it triggers an ajax call that updates the score_up value. I can't seem to figure out what's wrong. I attempted using Firebug, but it doesn't detect the JavaScript. Any help would be appreciated! Here is the jQuery ...

Executing a file upload using ng-click="upload('files')" within Selenium Webdriver

Is it possible to automate a file upload when the HTML code does not include an < input type='file' > instead, uses a link <a ng-click="upload('files')"> File Upload </a> Clicking this link opens a file selector f ...

I encountered an issue when attempting to execute an action as I received an error message indicating that the dispatch function was not

I just started learning about redux and I am trying to understand it from the basics. So, I installed an npm package and integrated it into my form. However, when I attempt to dispatch an action, I encounter an error stating that 'dispatch is not defi ...

Utilizing Radio Buttons for Table Selection in a React Application

Currently, I am utilizing React, MUI, and Formik in my project. My task involves implementing a table where only one radio button can be selected per row. How can I achieve this functionality? If you want to take a look at my code, it's available on ...

Is it possible to further simplify this piece of JavaScript using jQuery?

In my journey to learn and grow with Javascript, I have come across a snippet of code that simply attaches an onclick event to a button and updates the text of an em tag below it. As I delve deeper into jQuery, I am beginning to appreciate its syntax and u ...

The request to http://localhost:3000/cartdata has encountered an internal server error (500) in the isAxiosError.js file at line

Error Image I'm currently working on developing a shopping cart feature, and I've encountered an issue when transferring data from the client side to the server side. Despite the cart data being successfully updated in the session, an internal se ...