The functionality of broadcasting events and using the 'on' method seems to be malfunctioning

I'm facing an issue where I am attempting to send an event from one controller to another and listen for it, but the data is not being displayed on the DOM. Interestingly, there are no errors present. When displaying regular $scope variables from both controllers, it works fine. It seems like the broadcast and on functionality are not working as expected, and since there are no errors, debugging becomes a challenge.

oneApp.controller("twoController",["$log","$scope","$rootScope",function($log,$scope,$rootScope){
var str ="sent from twoController ";
$scope.hey = 215;
$rootScope.$broadcast("hey",str);

}])

oneApp.controller("twoChildController",    ["$log","$scope","$rootScope",function($log,$scope,$rootScope){
//var str ="sent from twoController ";
//$scope.display = str;
$scope.$on("hey",function(event,str){
$scope.display = str;
});

}])

If anyone could assist me in resolving this issue, I would greatly appreciate it.

Answer №1

When controller1 is initiated before controller2, a broadcast event occurs from controller1 before controller2 has registered with $on. To solve this issue, you can use $timeout.

var app = angular.module("myApp",[]);

//controllers declaration
app.controller('myCtrl1',function($scope, $rootScope, $timeout){
  $scope.name = "Roger";
  
  $timeout(function(){
    $rootScope.$broadcast('hey',$scope.name);
  });      
    
});

app.controller('myCtrl2',function($scope, $rootScope){
    $scope.$on('hey',function(event,name){
      $scope.name=name;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp"> 

<div class="div1" ng-controller="myCtrl1"> 
     <span>myCtrl1 : {{name}}</span>
</div> 

<div class="div2" ng-controller="myCtrl2"> 
    <span>myCtrl2 : {{name}}</span> 
</div> 
 
</body>

Answer №2

Here is one way to approach it:

To start, make sure all your broadcast events are defined in a central controller like this:

$rootScope.broadcast.actions = {
        hello : 'hello',
        // include all other broadcast events here
}

When you want to send a broadcast event:

$rootScope.$broadcast($rootScope.broadcast.actions.hello,{message});

And when you need to receive a broadcast event:

$scope.$on($rootScope.broadcast.actions.hello, function (event,message){
    $scope.displayMessage = message;
});

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

Steps to manage the time delay between mousewheel events triggering

Currently, I am working on a website for a movie production company that showcases their various films in full-screen mode. Each video is listed and there is a function that automatically takes the user to the next video when a mousewheel event occurs. How ...

Error in jQuery syntax when parsing a correctly formatted JSON object

My goal is to retrieve Instagram user details using jQuery ajax, which can be found at the following URL: https://www.instagram.com/instagram/?__a=1 However, when I try to make the Ajax call with the code below: $(document).ready(function(){ var instag ...

Tips on how to stop jQuery DataTable tools from being redrawn following a page reload

While using jQuery DataTable, I have encountered an issue with the tools such as filter and checkbox. Every time I call table.ajax.reload(), all the tools are rendered again on the callback of the AJAX request, causing the checkbox values to not be retai ...

Obtaining and implementing MongoDB array operations

Currently, I am in the process of developing a website that utilizes a Node.js server connected to a MongoDB database. Specifically, for one of the pages on my site, I plan to extract an array from the Mongo database and utilize it to dynamically generate ...

Tips for displaying dynamic data in a bootstrap tooltip with HTML contentInstead of regular tooltips, you

I am attempting to populate data from the grid within a tooltip. This tooltip is triggered when the user hovers over the first column inside the ui-grid. I am using Bootstrap and the HTML of the tooltip is displaying correctly as intended. Despite trying v ...

Updating with Setstate

Refreshing the page with Setstate, registering twice and doubling the count of both heads and tails counter every time on click instead of adding just +1 class CoinFlip extends Component { constructor(props) { super(props); ...

Bringing in d3js into Angular 2

Is there a way to successfully import d3js into an Angular2 project? I have already installed d3js using npm and added it to my systemJs, but am encountering a traceur.js error. I also attempted to just use the latest cdn in a script tag and tried import * ...

Calculating numbers with Math.ceil will result in an increase of 1

After using Math.ceil, one value was rounded up to 50 and the other to 80. However, when I added these two values together, the result unexpectedly turned out to be 131. console.log(Math.ceil(e.currentTarget.clientHeight) // 50 console.log(Math.ceil(e.cu ...

What methods can I use to enhance the functionality of a constructor/prototype function?

In this scenario, I have a constructor set up as follows: function Individuals(lastName) { this.lastName = lastName; this.firstName = []; } Additionally, there is a prototype defined like so: Individuals.prototype.getFirstName = function() { getName(); ...

Utilize a React Hook that fetches data from an API upon clicking two distinct buttons

I have developed a next.js application integrated with mongoDB as the database. Currently, there are two buttons in my app (Delete, Save). I want the functionality such that clicking the 'Delete' button will trigger a fetch request to delete dat ...

What is the process of transferring JavaScript code to an HTML file using webpack?

I am looking to display an HTML file with embedded CSS, fonts, and JS (not linked but the content is inside). I have the CSS and fonts sorted out, but I am struggling to find a solution for the JavaScript. My project is based on Node.js. ...

Guide on exporting a reducer from a Node module built on React Redux

I am currently working on a project that requires importing a component from an external node module. Both the project and the component utilize React and Redux, and I intend for them to share the same store. Below is a snippet of the reducer code for the ...

How can one extract dates from a range using mongoose?

Currently, I am working on a rental app project. One of the key functionalities I am trying to implement is the ability to determine the availability of cars between two specified dates, including those dates themselves. Within the database, I have two mai ...

Implementing class changes based on scroll events in JavaScript

const scrollList = document.getElementsByClassName('scrollList'); function scrollLeft() { scrollList.scrollLeft -= 50 } function scrollRight() { scrollList.scrollLeft += 50 } #scrollList { display: flex; overflow: auto; width: 10 ...

When attempting to delete an item from Firebase using React, the re-render results in the item being

I'm currently in the process of developing an app to enhance my React skills, and I've chosen Firebase for data storage. Everything seems to be working fine as all items from Firebase are rendering properly. However, I've encountered an issu ...

Axios is unable to retrieve data in React render, but it is successful when accessed through the console

I am currently in the process of developing an e-commerce website and encountering an issue with rendering image data stored in MongoDB. The goal is to fetch the image data using axios and display it on the website. However, despite successfully fetching t ...

Navigate through the options on the left menu by sliding your

I'm attempting to create a menu that slides in a submenu from the left on hover, but the issue is that with this code, all submenus open instead of just the one related to the hovered link. Here is my HTML code: <ul id="NavMenu"> ...

The value of req.body.stripeToken is not defined

I am facing an issue while using $http to post a form to my nodejs server. Upon posting, I attempt to retrieve the variable stripeToken using req.body.stripeToken in my server code, but it always returns undefined. Interestingly, when I make the post requ ...

Unable to adjust the size of a DIV with a button click in Vue3

I am having trouble resizing a DIV block in Vue3. Whenever I click the button, I receive an error message saying "Cannot read properties of undefined (reading 'style')". I know there is an issue with the JS part of the code, but I'm not sure ...

Set the background color of the Material UI Drawer component

Need some advice on changing the background color of Material UI's Drawer. I've attempted the following approach, but it's not producing the desired result. <Drawer style={customStyle} open={this.state.menuOpened} docked={false} ...