"Utilizing AngularJS event system through $broadcast and $on

I have recently started learning AngularJS and I am trying to send a message from one controller to another. I have looked at various examples and my code seems to be similar, but it is not working. Why is $rootScope.$on not working? Can anyone help me with this?

HTML:

<div ng-controller="Ctrl">
    {{message}}

    <div ng-controller="Ctrl1">
        <p>Ctrl1</p>

        {{test}}
    </div>
</div>

Ctrl:

angular
    .module("app")
    .controller("Ctrl",["$rootScope","$scope",Ctrl]);

function Ctrl($rootScope,$scope){

    var test = "Bla bla bla!";
    $scope.message = test;

    $rootScope.$broadcast('aaa', test); 
}

Ctrl1:

angular
    .module("app")
    .controller("Ctrl1",["$rootScope","$scope", Ctrl1]);

function Ctrl1($rootScope, $scope){

    $rootScope.$on('aaa', function(event, args){
        console.log("This message doesn't appear!");
        $scope.test=args;
    });

}

Answer №1

The issue arises because the Parent controller Ctrl is registered before the Ctrl1 controller is loaded. As a result, the listener for the $broadcast event in the inner controller Ctrl1 has not been registered yet.

To resolve this issue, you can ensure it works by using a $timeout function in the parent controller to delay the $broadcast of the event, allowing it to be evaluated in the next digest cycle.

$timeout(function(){
   $rootScope.$broadcast('aaa', test); 
})

Check out the demo here

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

Creating a virtual roulette wheel with JavaScript

I'm currently working on creating a roulette wheel using JavaScript. While researching, I came across this example: , but I wasn't satisfied with the aesthetics. Considering that my roulette will only have a few options, I was thinking of using ...

Using jQuery.ajax to manage caching and manipulating timestamps

Currently, I am utilizing the jquery.ajax techniques to transmit GET-requests to the server, with caching disabled by setting cache to false. Everything seems to be working fine so far. It appears that jQuery automatically includes a timestamp (likely epo ...

Revealed the previously hidden private variables within the Revealing Module Pattern

I have encountered an issue while implementing the Revealing Module Pattern, as I am struggling to expose a modified private property. var myRevealingModule = (function(){ var name = 'Samantha'; function updateName () { name = ...

I am encountering an issue where req.body is returning as undefined

After creating a controller with the code below: app.post('/users', (req, res) => { console.log(req.body); const user = new User({ name: req.body.name, email: req.body.email }); user.sa ...

Update all project files in Firebase authentication

A client-side project is being developed using firebase and vue. After a successful login by the user, the authService object gets updated in the Login component, but not in the router. The authService is utilized in both the Login component and AdminNavba ...

The NgFor is unable to iterate over an array because it is being treated as an

When attempting to call a new endpoint for displaying data, I noticed that the previous set of data is wrapped with an extra pair of brackets '[]', which seems to be causing a problem. The new endpoint does not format the data in this way when I ...

Discover the best practices for utilizing CSS selectors reliably in puppeteer

For a project, I am currently working on customizing a puppeteer script that is able to play a song from Soundcloud and record it. The main goal is to utilize a CSS selector to display the duration of the song as well. I am encountering difficulties with g ...

Best practice for detecting external modifications to an ngModel within a directive

I've been working on creating a directive that can take input from two sources and merge them into one. To achieve this, I'm monitoring changes in both inputs and updating the combined value in the ngModel of my directive. However, there's ...

AngularJs FileList Drag and Drop Feature

Being brand new to front-end development, I decided it would be a fun challenge to implement drag and drop functionality on an existing upload page. However, as I began integrating ng-flow (a directive that helps with drag and drop), I encountered difficul ...

Disabling the child element from triggering the parent element's onclick function, while still allowing it to respond to its own content

My list elements have onclick-functions that change the display of each element and its child div, moving them to the top of the list. Clicking again reverses this effect. The issue arises because the child div contains search fields, clickable pictures, ...

How can child components in ReactJS be conditionally rendered based on the status of userData loading?

It seems like there might be an issue with how we handle user login in our application. Whenever a user logs in, the redux state is updated with the server response. Many components rely on this logged-in status. We pass the currentUser object down to all ...

The unrevealed node that is requesting the module is leading to an undefined outcome

I'm facing an issue where I need to import var server = require('../../index.js'); in my foo-dao.js file. This is necessary for accessing a hapi server plugin without passing it through the hapi request object from controller to dao. The pr ...

Images that are automatically generated cannot be interacted with by clicking on them

I currently have 4 images loaded onto my website. Whenever I click on one of the images, it becomes highlighted as desired using the following code: JavaScript Function 1 : var ImageSelector = function() { var imgs = null; var selImg = null; retu ...

Tips on creating a horizontal scrolling effect using the mouse

Is there a way to enable horizontal scrolling by holding down the mouse click, instead of relying on the horizontal scroll bar? And if possible, can the scroll bar be hidden? In essence, I am looking to replicate the functionality of the horizontal scroll ...

"An issue with the colyseus server has been detected within the JavaScript code

I have written some code but it seems to be causing errors. const colyseus = require("colyseus"); const http = require("http"); const express = require("express"); const port = process.env.port || 3000; const app = express(); ...

Implementing a feature to dynamically add multiple markers on Google Maps

Currently, I am utilizing the .text() method to extract latng from the html. <div class="latlng"> -33.91722, 151.23064</div> <div class="latlng"> -32.81620, 151.11313</div> As a result, I am using $(latlng).text() to retrieve the ...

Reviewing the element names in a jQuery-selected array of objects

I'm new to javascript and the jquery library and I need to work with an array of input fields that have specific names for validation. Each input field is named NS[0], NS[1], etc., and the total number of these fields is generated dynamically in the c ...

transferring information from a nested input field in Vue to its parent component

I need to send the input data from a child component to the parent component's data property by using the $emit method. Directly binding the transmitted property to the child property using v-bind within the <input v-model="userinput" /&g ...

Unable to assign value to Ref data property in Vue3 due to undefined item

Recently, I've been utilizing Vue3 and Nuxt3 to work on a project. My main task involves extracting the :id parameter from the URL and checking if it matches an ID in a JSON file. If there is a match, I update a reference data point called 'exist ...

Guide on implementing route segments using $location.path() in Angular

I am currently utilizing the routesegment provider for routing within Angular. I have a question regarding how to initiate a URL call using $location.path(). Here is my code snippet for reference: FinancialGameApp.config(['$routeSegmentProvider& ...