The broadcast message from AngularJS (1.2.25) $rootScope.$broadcast('message', data) appears to be failing to reach the corresponding $scope.$on('message') listener

I'm struggling with getting a $scope variable to trigger the screen to rebind. I have attempted calling $scope.$apply() and $digest() after assigning $scope.value = value, but I encounter an error "$rootScope:inprog] $digest already in progress.

To troubleshoot, I tried using my $rootScope.$on('message'function(){}) listener to create a secondary $broadcast to all scopes. However, the registration of the event on my $scope is not firing, which may be related to the same issue...or maybe not. Check out my code below:

Unfortunately, I can't provide a fiddle due to network policy restrictions.

Manifest:

  • [config]
  • [index.html]
  • [foo.html]
  • [ctrl]

[config] (a couple of attempted hacks. They're marked with comments)

    var kata = angular.module('kata',[
        'ngRoute'   
    ]).run(['$rootScope',
    function($rootScope){
        $rootScope.$on('message:foo',function(event,data){
            $rootScope.$broadcast('message:bar',['foo1','foo2','foo3']);//send secondary msg
            $rootScope.data = data; //Hack #1: When I couldn't get $scope to rebind, I tried to use $rootScope;still doesn't rebind.
        });
    }]);

kata.config(['$routeProvider',
    function($routeProvider){
        $routeProvider
            .when('/Foo',{
                templateUrl: 'foo.html',
                controller: 'FooCtrl'
            });
}]);

[index] (nothing funny here)

<html ng-app="kata">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1"></meta>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>

        <script src="./routingConfig.js"></script>
        <script src="./controllers.js"></script>        
    </head>
    <body>
        <div class="view-container">
            <div ng-view class="view-frame"></div>
        </div>
    </body>
</html>

[foo.html] (nothing funny here) A couple of tests with a couple of $scope variables attached to same stuff. Neither of these update

<div>
    This page is for capturing Data

    Data: {{data}}
    <hr />
    <ul>
        <li ng-repeat="foo in foos">
            <span>Foo Found!</span>
        </li>
    </ul>
</div>

[ctrl] (created several variables on scope trying to attack this problem in different ways)

var kataCtrl= kata.controller("FooCtrl", 
    [        '$scope', '$http','$rootScope','$location'
    ,function($scope,   $http,  $rootScope , $location) {
        $scope.data = "Foo";
        $scope.data1 = "[placeholder]";
        $scope.foos = [];


        //fires, assigns, view does not update
        $scope.$watch(function(){
            return $rootScope.data;
        }, function(){
            $scope.foos = ['data','foo','bar','baz'];<=Assignment succeeds. View does not update
            $scope.$apply();//<=Does nothing apparent; View does not update
            $scope.$digest();//<= Console Error. Already in digest loop
        },true);


        //does not fire
        $scope.$on('message:foo',function(event,data){ //<= This never catches
            $scope.data = data; 
        });


        //fires, assigns, View does not update
        $rootScope.$on('message:bar',function(event,data){
            $scope.foos = ['data','foo','bar','baz'];
            $scope.foo1 = data.element1;
            $scope.data = "[Foos returned from $rootScope]";
            $scope.$apply();//<= Does not help. Changing to $scope.$digest() indicates already in digest loop
        });
}]);

As a recap, $rootScope.$on() inside my config fires properly and assigns values to variables on $rootScope correctly. $rootScope.$broadcast generates a secondary message successfully. The controller's $scope.$on registration of the message does not catch. The controller's $rootScope.$on registration fires and assigns values on $scope, but the view does not rebind. Calling $scope.$apply() does not help, and calling $scope.$digest() simply reports that a digest loop is currently running.

Scoped variables are assigned to but the view never rebinds.

What could possibly be causing this issue?

Answer №1

It seems like the issue lies in broadcasting 'message:bar' while listening to 'message:foo' in the controller. I have created a simplified version of your code where you can see that my code emits an event to the root scope and receives the broadcasted event in the child scope:

<html ng-app="kata">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1"></meta>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
   
    </head>
    <body>
        <div class="view-container" ng-controller="FooCtrl">
            <div class="view-frame">
            <div>
                This section is designated for capturing Data
                <br>
                Data: {{data}}
                <hr />
                <ul>
                    <li ng-repeat="foo in foos">
                        <span>Foo Found!</span>
                    </li>
                </ul>
            </div>
            </div>
        </div>
        
        <script>
            var kata = angular.module('kata', [
                'ngRoute'   
            ]).run(['$rootScope',
                function($rootScope) {
                    $rootScope.$on('message:foo', function(event,data){
                        $rootScope.$broadcast('message:bar',['Data', 'from', 'root', 'scope']);//sending secondary message
                    });
                }]);

            kata.controller("FooCtrl", ['$scope', '$http','$rootScope','$location',
                function($scope, $http, $rootScope, $location) {
                    $scope.data = "Foo";
                    $scope.data1 = "[placeholder]";
                    $scope.foos = [];

                    $scope.$on('message:bar', function(event,data){
                        $scope.data = data; 
                    });
                    
                    $scope.$emit('message:foo');
                }]);
        </script>
    </body>
</html>

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

Issue with socket.io: Server unable to emit event to client upon connection

I'm struggling with my basic socket.io setup as I can't seem to get my server to send a message once the connection is established. Upon establishing a connection to my server, I want it to automatically send a message back to the client. Here&a ...

When the directive name conflicts with the attribute name

My issue arises from conflicting directive and attribute names. Here's the scenario: I have two directives, where the name of the first directive matches an attribute name of the second directive: angular.module('mymodule').directive(' ...

View the selected radio buttons and checkboxes next to each other in real-time before finalizing and submitting

Within my form, individuals have the option to select from radio buttons and checkboxes. The challenge is that I need to display the chosen data on the page before they enter their email and submit! Since I cannot refresh the page, PHP won't work for ...

Utilizing a variety of textures across various surfaces of a single geometry

I'm new to working with Three.js and I have a question about displaying multiple images over a plane geometry. Here is the scenario: Imagine a simplified case where we have a plane divided into tiles like this: +---+---+---+ | 1 | 2 | 3 | +---+- ...

Manipulating and filtering an array of objects in JavaScript/jQuery

Looking to simplify my array manipulation in Javascript, I need to subset based on key-value matches. I have an array called js_obj, and my goal is to modify objects where a certain condition is met. Consider the structure of my array: js_obj = [{ wo ...

Comparing XDomainRequest and XMLHttpRequest for IE8 and IE9: A detailed analysis

I am feeling pretty lost when it comes to understanding the XMLHttpRequest and XDomainRequest renaissance, and I could really use some guidance. Here are my thoughts so far: It seems like the XDomainRequest in IE8 and IE9 is some sort of subclass of XMLH ...

Trouble with Angular: Passing output between child components is not working

Just dipping my toes into Angular, I started learning it yesterday for a take-home job interview project. Please excuse any rookie mistakes in advance. For some hands-on practice, I decided to work on a basic project where the main component (app) has two ...

Ways to retrieve a variable from a separate TypeScript document

A scenario arises where a TypeScript script contains a variable called enlightenFilters$: import { Component, Input, OnInit } from "@angular/core"; import { ConfigType, LisaConfig } from "app/enrichment/models/lisa/configuration.model"; ...

Is there a way to utilize variables from a source XML file to establish points on an SVG polygon?

I've been struggling to figure out if it's possible to dynamically set points on an SVG polygon using variables that are defined by an XML document which is constantly changing. All I want is to set the path like this: var polygonToUse = window. ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...

Incorporating a new Autodesk Forge extension

Hey there! I'm currently working on integrating a forge extension into my viewer, but I seem to have missed something along the way. I've been following this helpful guide: Here's the code snippet that I'm using: <body> < ...

How can I redirect to a different URL using Ajax when successful POST request is made?

Here is the code snippet I am working with: $.ajax({ type: "POST", url: "/pro_signup", data: { data: data, key: key }, dataType: "json", success: function (response) { document.getElementById("pu ...

Troubleshooting: AngularJS ngClick function malfunctioning with dynamically inserted HTML

In my app, there is a single input element with a mylist model. When mylist=1, I include first.html and when mylist=2, I include second.html. The issue arises when trying to change the value of mylist by clicking a button within each HTML template. To ach ...

Angular Circumstance

Can you help me out? I am trying to figure out how to create an IF...ELSE condition using AngularJS on my index.html file: <ons-list-item modifier="chevron" class="list-item-container" ng-repeat="item in categories track by $index"> <a href="#/pa ...

customizing configurations for different environments in AngularJS

Currently, I am in the process of developing a website using Angularjs and WebAPI as the backend support within Visual Studio. In my app.config.js file, I have defined the URL to the WebAPI as an app constant: var serviceBase = 'http://localhost ...

Share these Node.js REST API functions for export

I am in the process of exporting some REST API functions from a module using node.js with restify. Within my project, there is a file named rest.js where I have defined these APIs. module.exports = { api_get: api_get, api_post: api_post, }; var ...

Exploring elements with Watir WebDriver and ExtJS

Currently, I am performing an acceptance test using watir-webdriver with Ruby. I have a question regarding ExtJs support with Watir webdriver. Is it possible to locate elements that are dynamically generated by ExtJS? I have attempted the following: @brow ...

What are the steps to download files using vuejs?

I need assistance with enabling users to download a file from my website. The variable item.upload_attachment holds the link for the file, such as localhost:8000/media/uploads/poppy.docx. I want to make this link clickable so that users can easily download ...

What is the best way to connect an HTML image to effortlessly switch between displaying and hiding an element (specifically, a table) using JavaScript?

Apologies if my question is a bit confusing and poorly written, as I am new to coding and Stack Overflow. What I am trying to achieve is the ability to click on each image and have a different table pop up for each planet with facts (an example of the Merc ...

The onBlur function is preventing link clicks from being registered

My Navigation Bar includes a React-InstantSearch: <SearchBox /> component that provides Autocomplete functionality. The SearchBox triggers an onChange event to display suggestions, and an onBlur event to hide the box when exiting the search field. Ho ...