Angular JS sending a message to various views, including a pop-up modal

One of the services I have created is designed to manage message broadcasting to controllers that require it.

The service implementation:

.factory('mySharedService', function($rootScope) {
  var sharedService = {};

  sharedService.message = '';

  sharedService.prepForBroadcast = function(msg) {
    this.message = msg;
    this.broadcastItem();
  };

  sharedService.broadcastItem = function() {
    $rootScope.$broadcast('handleBroadcast');
  };
  return sharedService;
}); 

The controller (cntl):

function AlertCtrl($scope, mySharedService) {
  $scope.msgs = [];
  $scope.$on('handleBroadcast', function() {
    $scope.msgs.push(mySharedService.message);
  });  
  $scope.closeAlert = function(index) {
    $scope.msgs.splice(index, 1);
  };
}

The HTML structure (html):

<div ng-controller="AlertCtrl">
  <alert ng-repeat="msg in msgs" type="msg.type" close="closeAlert($index)">{{msg.msg}}</alert>
</div>

The broadcasted message appears correctly when inserted anywhere in the HTML except within a modal window. How can I make it display in the modal window?

You can find the code example on Plnkr: http://plnkr.co/edit/l6ohBYRBMftpfxiKXvLr?p=preview

Answer №1

On the main page, there is a single AlertCtrl instance, but a new instance is created each time the modal is opened (confirm this by adding console.log statements). The AlertCtrl within the modal is initialized and begins listening for events only after the event has been broadcasted.

Answer №2

If you want to send custom arguments with the $broadcast method in AngularJS, here's how you can do it:

$rootScope.$broadcast('customEvent', 'your data here');

Then, in your listener function:

$scope.$on('customEvent', function(event, data){
    $scope.items.push(data);
});

For more information, check out: http://docs.angularjs.org/api/ng.$rootScope.Scope#methods_$broadcast

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

ReactJS Issue: Failure of Validation on Auto-Populated Form Field

I encountered an issue with the validation setup in my form. The validation checks the input values for "required", "max length", and "min length". Oddly, the validation only works for fields where the user manually types into the input field. I made some ...

Bug encountered in the Twitter Bootstrap accordion component

I've been struggling to pinpoint my error for the past few hours. I'm using Bootstrap accordion along with a handlebars template engine, and overall it's functioning correctly with the values from my database. The issue arises when initiall ...

Display directional arrow on Ext.grid when the page is initially loaded

Displaying a grid with the product ID is our current setup. While the data is sorted according to the product ID, the sort arrow does not display upon page load. I have observed that clicking on the column reveals the arrow. How can we ensure that the so ...

Wordpress is experiencing a recurring issue with scripts being loaded multiple times

Currently, I am attempting to load some of my scripts from CDNs such as CDNjs and Google. While the scripts are loading correctly, I have noticed a strange issue where each script seems to generate two or even three HTTP requests (for the same script). You ...

Troubleshooting a configuration problem with Mean-cli

Recently, I've ventured into developing mean based apps. I'm currently following the steps outlined here to configure the app. Despite installing all necessary prerequisites as instructed in the link, I encountered an error while working on Windo ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...

Clear v-model without changing its associated values

I'm facing an issue with my <input> fields, which look like this: <input type="text" v-model=user.name" /> <input type="text" v-model="user.phone" /> <button @click="add">add user</button> Whenever the add user button i ...

(node:2824) UnhandledPromiseRejectionWarning: ReferenceError: The variable "role" has not been declared

I am currently in the process of getting my discord bot up and running again. The issue is that he is old, and in the previous version, this functionality worked. However, after reading other posts, I discovered that in order to make it work, I need to u ...

Is there a way to abruptly terminate a node thread from my frontend application?

My React web application is designed to generate solutions for Rubik's cubes. Whenever a user inputs a query on my site, it triggers a computation process that can take anywhere from 1 second to 240 seconds. Each time a solution is found, the state is ...

Is there a way to access and troubleshoot the complete source code within .vue files?

I've been struggling for hours trying to understand why I'm unable to view the full source of my .vue files in the Chrome debugger. When I click on webpack://, I can see the files listed there like they are in my project tree, but when I try to o ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

Changing the main domain of links with a specific class attribute during an onmousedown event - is it possible?

We are facing a situation where we have numerous webpages on our blog that contain links from one domain (domain1.com) to another domain (domain2.com). In order to avoid manual changes, we are attempting to achieve this without altering the link (href). Th ...

Developing a quiz using jQuery to load and save quiz options

code: http://jsfiddle.net/HB8h9/7/ <div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Add a Multiple Choice Question </label> <br /> <textarea name ...

Invoke a function within one component using another component

I am facing an issue with deleting playlists displayed on my page. These playlists are fetched from an external API and each playlist has a delete button which is supposed to remove the playlist both from the API and the view. The deletion process works s ...

Tips for resolving the Error: Hydration issue in my code due to the initial UI not matching what was rendered on the server

export default function Page({ data1 }) { const [bookmark, setBookmark] = useState( typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('bookmark')) : [] ); const addToBookmark = (ayatLs) => { s ...

I'm trying to understand a JSON object that has multiple key names pointing to a single value. How can I properly interpret this in

Encountering an object with a strange key. const obj = { formValues: { 'TOTAL;_null_;_null_;3;_null_': "100" 'billing;_null_;_null_;1;_null_': "Y" 'billing;_null_;_null_;2;_null_': "Y" 'billi ...

Monitor files in different directories with the help of pm2

Can pm2 detect changes in directories outside of the current one? For example, if I have an index.js file in /home/sprguillen/workspace/node that needs to be run by pm2, but my configuration file is located outside in /home/sprguillen/workspace/config. I ...

Unique rewritten text: "Displaying a single Fancybox popup during

My website has a fancybox popup that appears when the page loads. I want the popup to only appear once, so if a user navigates away from the page and then comes back, the popup should not show again. I've heard that I can use a cookie plugin like ht ...

Converting PHP variables to JavaScript variables: A step-by-step guide

I'm trying to figure out the most efficient method for retrieving PHP variables using AJAX and then transforming them into JavaScript variables. Imagine I have the following code in my PHP file: echo $total; echo $actual; Edit: JSON echo json_enco ...

What is the process for setting up a resthook trigger in Zapier?

I'm currently integrating Zapier into my Angular application, but I'm struggling with setting up a REST hook trigger in Zapier and using that URL within my app. I need to be able to call the REST hook URL every time a new customer is created and ...