AngularJS offers a helpful solution for exchanging data across controllers by utilizing the $broadcast method

I've been struggling with utilizing $broadcast and $on functions to transfer data between two controllers.

On my main webpage, there is a button that increments a variable by 4 each time it's clicked:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body ng-app="app">
    <div ng-controller="mainCtrl">

        <button ng-click="add(4)"> 4 </button>

    </div>
    <script src="../Scripts/angular.js"></script>
    <script src="../assets/js/angular-grid.js"></script>
    <script src="../assets/controller/gods_controller.js"></script>
    <script src="../Scripts/angular-animate.js"></script>
</body>
</html>

In my mainCtrl, I have the add() function which uses $broadcast to send out the updated value:

var module = angular.module("app", ["angularGrid", "ngAnimate"])

module.controller("mainCtrl", function ($scope, $rootScope) {

var total = 0

    $scope.add = function (x) {
        total += x;

        $rootScope.$broadcast('totalBroadcast', total)

    }

});

Then, I have another controller for a popup using $on to receive the broadcasted data:

module.controller('popUpCtrl', function ($scope) {


     $scope.$on('totalBroadcast', function(events, args){

  $scope.total = args;
  })

   })

The HTML for the popup utilizes the second controller and displays {{total}} as an expression:

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body ng-app="app">
    <div ng-controller="popUpCtrl">

       <p>The total is: {{total}}</p>

    </div>
    <script src="../Scripts/angular.js"></script>
    <script src="../assets/js/angular-grid.js"></script>
    <script src="../assets/controller/gods_controller.js"></script>
    <script src="../Scripts/angular-animate.js"></script>
</body>
</html>

However, no data seems to be passed to the second controller, and the expression shows nothing at all.

EDIT


I also attempted to use a service. The HTML remains the same, but now a service has been added.

module.factory('myService', function () {

    var total = 0;

    var setTotal = function (x) {
        total = x;
    }

    var getTotal = function () {
        return total;
    };

    return {
        setTotal: setTotal,
        getTotal: getTotal
    }


    });

The main controller and add function are now:

 module.controller("mainCtrl", function ($scope, myService) {

    var total = 0

    $scope.add = function (x) {

        myService.setTotal(x)
    }

 });

The popUpCtrl controller is now:

module.controller('popUpCtrl', function ($scope, myService) {


    $scope.total = myService.getTotal();

})

{{total}} in the popup now displays the initial "0" which is what the variable total is set to in the service. The data is being transferred using the service, but the setTotal() method doesn't seem to be updating the variable as expected by the add() function. Both controllers have the service injected as a dependency.

Answer №1

Avoid using watches or broadcast to share data between controllers; instead, utilize a common service for this purpose.

Services offer an efficient method for sharing data and functionality throughout an application. These services act as singletons that can be injected into controllers and other services, making them perfect for writing reusable code.

For more information, visit the following link:

Answer №2

The reason for receiving a value of zero is due to the fact that your controller only assigns the value of myService.getTotal() during loading. This means that any changes made to the total variable will not be reflected.

To resolve this, you should implement a $watch function for updates:

$scope.$watch(function () {
    return myService.getTotal();
}, function (newVal) {
    $scope.total = newVal;
});

In addition, it appears that you are re-initializing your app with new pages. Angular does not function in this manner. I recommend researching angular route and following the steps I have provided here. By converting it into a single-page app, you should see successful results.

Answer №3

After some research, I discovered a solution to my original query by utilizing the

localStorage.setItem("num", "num")
function to store data in the web browser. This method was specifically designed for sharing data between tabs or windows, making it accessible through localStorage.getItem("num").

Although this resolved my initial dilemma, I now seek a way to dynamically update the total without having to refresh the page each time. If anyone has any advice on how to achieve this, it would be greatly appreciated.


RESPONSE TO PREVIOUS QUESTION:

Implementing the following event listener in my secondary popup enabled me to effectively update the total -

window.addEventListener('storage', function (event) {
        $scope.total = parseInt(event.newValue);
        $scope.$apply();
    });

This allowed me to access the stored data and bind it to an expression within my HTML code. It's important to note that calling $scope.apply() is necessary in this case since the total is outside of the scope.

For more detailed information, please refer to this resource - https://developer.apple.com/library/safari/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Name-ValueStorage/Name-ValueStorage.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

Refresh a table using jQuery Mobile, PHP, and AJAX without having to reload the entire page by clicking a

Currently, I am working on a web app that includes a pop-up feature. When the user clicks on the pop-up to close it, I want the table data to refresh without having to reload the entire page. This pop-up allows users to modify existing data in the table. A ...

Adding new elements to a div container

My goal is to populate a div element with items based on elements from an array. I need to duplicate an existing element on the page and append the new version to the div. Let me provide the code for better understanding: JavaScript: function apply(list ...

Tips for keeping a character from rotating while moving diagonally on a slope

When moving at an angle to the collider, the issue becomes apparent: https://i.sstatic.net/k3fF1.gif Although I am using OimoPhysics, there seems to be no specific tag for this. This problem is commonly encountered in all physics engines. The scenario in ...

Issue encountered when populating the list of orders along with an array of merchandise items

I am currently in the process of developing an e-commerce website using React, Node, and MongoDB. The order schema I created includes the cmdRef (string), the client ID, and an array of products (with product IDs and quantities) as shown in the code below: ...

A guide to showcasing object array data within a map component in reactjs without any duplicate entries

Looking for assistance with ReactJS I have the following data and I am trying to display it without duplicates. Essentially, I want each unique category ("A", "B", and "D") to be displayed only once. I aim to achieve this within the map function provided ...

open() the html file containing dojo elements

I have a simple Dojo chart that functions perfectly in a separate document. However, here lies the issue, When I use $('#result').load('dojo.html'); to import the file, nothing occurs - the page does not load the graph. On the other h ...

What are some alternative methods for downloading the latest file version without relying on the client cache?

On my webpage, I have a table displaying users' data. Each row represents a user and includes their business card, which is a clickable tag that opens a PDF file stored on the server. <td class="business_card"> <a href="/static/users_doc ...

Unselect a radio button

I am currently utilizing the bootstrap radio buttons and I want to implement a feature that allows for deselecting a radio group. I came across an approach in this (Fiddle), which involves using an additional button. Instead of adding a separate button, my ...

The product image does not display any other images

Hey, I'm experiencing an issue and need help replicating the photo changing effect on this website: I've managed to do everything right except for the photo changing feature (1 / 2 / 3 / 4)!! Here's what I have so far: Can anyone assist m ...

Oops! The provided value for the argument "value" is not a valid query constraint. Firestore does not allow the use of "undefined" as a value

I encountered an error while exporting modules from file A and importing them into file B. When running file B, the error related to Firebase Cloud Firestore is displayed. const getMailEvents = (startTime, endTime) => { serverRef = db.collection("Ma ...

Is there a way to hide the row select option for individual rows in MUIDatatables without affecting the multiple row select options?

Is there a way to hide the checkbox in the header row that allows selection of all rows at once? I prefer to manually select multiple options by clicking on each individual row. Can the row select option be hidden? https://i.sstatic.net/dfiJQ.png ...

Hold down for File Menu to appear

Can a long press be used for triggering file dialog? I came across an interesting discussion about Long Press in JavaScript, where they discuss how to trigger an event on a long press. However, this method may not work for triggering file input click in ...

Unlawful use of the return statement

Can you identify the issue with this code? The browser reports: "Uncaught SyntaxError: Illegal return statement" I'm looking for an explanation in this format: 1 2 3fool 4 5bar 6fool 7 8 9bar... let arr = []; for (i = 0; i <= 100; i++) { if ( ...

Arranging by and loading progressively in AngularJS

Encountering an issue with the orderBy function in an ng-repeat paired with an auto-incrementing limitTo. After loading a few elements on the page, the directive ceases to function properly and stops increasing the element limit. Here is the HTML code sni ...

Using a variable to contain a loop in Jquery

Seeking assistance with a jQuery function that retrieves values from a PHP form to create a variable for an ajax call. Is it possible to include a loop within a variable? Below is a snippet of my code to provide better context: ... var teacher_ids = $( & ...

Redirect user to a specific route in backbone framework after logging in using rails

My goal is to enhance user experience by redirecting them to the originally requested URL after logging into a secure section of the site. For example, if a user clicks a link in an email notification and tries to access: but is not logged in, they get re ...

What is the process for adding submitted data to an already-existing local JSON file?

I have a new Angular assignment that requires me to push form data into an existing JSON file locally. The task is to develop an Angular application where users can create new tasks and view them on a separate page. Initially, I attempted using http.post ...

The loss of Webgl context that remains unrecovered

I am facing an issue with the loss and restoration of webgl context. My application is quite complex, containing a lot of data, graphs, lists, and maps. Within the map section, I utilize webGL to ensure optimal performance. My code effectively manages th ...

What is the reason behind the warning "Function components cannot be given refs" when using a custom input component?

When attempting to customize the input component using MUI's InputUnstyled component (or any other unstyled component like SwitchUnstyled, SelectUnstyled, etc.), a warning is triggered Warning: Function components cannot be given refs. Attempts to acc ...

Can JavaScript executed within a web browser have the capability to manipulate files on the underlying host system's file system?

Is it possible to programmatically move files or folders from a website using code? I am aware that with Python and Node.js, this can be achieved through the OS, path, and fs modules. Can JavaScript running in a website also handle file management tasks ...