How to trigger a function across various controllers in AngularJS

We're in the process of creating an app using phonegap onsen and angularJS.

Attempting to invoke a function from a different controller has been challenging. Despite following various documentation such as this

Unfortunately, it's not working for me. Below is the code I've written so far.

module.run(function ($rootScope) {
    $rootScope.$on('some-event-here', function (event, data) {
        console.log('1');
        $rootScope.$emit('show-dialog-of-some-event', data);

        //I also tried
        //$rootScope.$broadcast('show-dialog-of-some-event', data); 
    });
});

module.controller('controller1', ['$scope', '$http',  function($scope, $http) {
    $scope.proceed = function() {
        console.log('0');
        $scope.$emit('some-event-here', {});
    }
}]);

module.controller('controller2', ['$scope', '$http',  function($scope, $http) {
    $scope.$on('show-dialog-of-some-event', function (event, data) {
        console.log('2');
        ons.createDialog('some-dialog.html').then(function(dialog) {                        
            //some code here
        });
    });
}]);

'0' and '1' are displayed on the console but '2' is not showing up.

This seems like a simple issue, yet I can't pinpoint the problem in my code.

Your help is greatly appreciated.

Answer №1

It seems that the issue lies in how you are handling event delegation for the 'show-dialog-of-some-event' event within controller2's local scope, specifically in $scope. When emitting an event from $rootScope, keep in mind that events bubble up and do not travel downwards. As a solution, consider defining the event handler for 'show-dialog-of-some-event' on the root scope instead, like so:

$rootScope.$on('show-dialog-of-some-event', function(event, data) {});

Answer №2

When it comes to communication between sibling controllers or from a parent controller to a child controller, the key is using $scope.$broadcast. However, if you need to communicate from a child controller to a parent controller, then $scope.$emit is what you should be utilizing.

Answer №3

If you find yourself not needing to process anything on rootscope, simply inject $rootScope into the controller.

module.controller('controller1', ['$scope', '$http', '$rootScope', function($scope, $http, $rootScope) {
    $scope.proceed = function() {
        console.log('0');
        $rootScope.$boardcast('some-event-here', {});
    }
}]);

module.controller('controller2', ['$scope', '$http',  function($scope, $http) {
    $scope.$on('some-event-here', function (event, data) {
        console.log('2');
    });
}]);

While using a service is cleaner, this pattern can be utilized if it's not too frequent.

Answer №4

There are two issues in your code that need attention:

1: The use of $broadcast for event propagation downwards in the scope hierarchy is incorrect. Instead, you should be using $rootScope.$broadcast to bubble events up the scope hierarchy. Here's the correct syntax:

$rootScope.$broadcast('show-dialog-of-some-event', data);

For more information on this topic, refer to this answer: $rootScope.$broadcast vs. $scope.$emit

2: Your module's run function is being executed before the controller attaches an event handler for the event. This means that by the time the event is configured in the controller, it has already passed. To fix this issue, follow these steps:

  • Change $emit to $broadcast
  • Delay the $broadcast call to a later point in the lifecycle so that the controller has attached its listener

Check out this Plunkr where I've adjusted the timing of the $broadcast call (in this case, when the window loads):

http://plnkr.co/edit/W7efiKqIlu4va4AcBTbG

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

Is there a method to verify the consumability of an API without having to make a direct request to it?

I'm working on an idle timer feature where the API will be called to update data once the timer runs out. How can I check if the API is still usable without actually sending a request? ...

Attempting to enable a checkbox using a controller located in a separate controller

I am attempting to trigger a checkbox from a separate controller. Suppose I have a card called information technology under one controller, and when clicked, it should redirect to another page that contains a checkbox for information technology managed by ...

Troubleshooting: Issues with AngularJs directive expression ID and ng-pattern functionality

When using a form input directive with ng-pattern, an error is displayed when the ID on the directive is a string. However, it fails to display the error when the ID is an expression. See the examples below: Example with working ID <form name="myForm" ...

Interacting with PHP through AngularJS Factory and receiving a response back to AngularJS

I am having trouble identifying the mistake. My PHP file is returning data in the format of ["9963648941","7416527247"], and I am attempting to retrieve this data using an Angular factory with an HTTP call as shown below app.factory("States", function ($h ...

Having trouble determining the total amount in my online shopping cart

I am facing an issue with the shopping cart I created, which consists of two components (Productlist and Cart List). When I click on the 'add to cart' button in the Product List, it successfully moves into the service file and then to the Cart Li ...

Generated Form Data Automatically

Seeking advice on achieving a specific functionality in ASP.NET Web Form that is similar to the AutocompleteExtender, but requires more flexibility. Here is what I aim to accomplish: There are 2 TextBox fields on the form: CompanyName and CompanyRef (a u ...

Guide for utilizing a table value as a parameter in a mySQL query with PHP

My website features an HTML table that is filled with data pulled from a mySQL table using PHP. Each row in the table is clickable, and when clicked, it opens a modal that contains a form to update and submit data back to the database using a mysql update ...

What could be causing my ajax file uploader to malfunction?

I am currently working on building an AJAX file upload module. Below is a snippet of the code I have been using: //creating a form for uploading files via AJAX FileUploader.prototype.createForm = function() { // creating a new form var form = docu ...

The onchange event does not seem to be functioning as expected in a dropdown menu that was dynamically added from a separate

Is there a way to display a list of tables from a database in a dropdown menu and allow users to select a table name? When a user selects a table name, I would like to show all the data associated with that table. The HTML file structure is as follows: & ...

The rollup-plugin-typescript is unable to identify the 'lib' option within the 'compilerOptions'

Currently, I'm following a tutorial on how to create an npm package. The tutorial can be found here. Here is the content of my tsconfig.json file: { "compilerOptions": { "target": "es5", "module": "es2015", "sourceMap": tr ...

The surprising twist of hasOwnProperty's behavior

I am currently working on a function that is designed to check whether an object contains keys such as 'id' or 'serif:id'. However, I have encountered some issues with its functionality. function returnIdPreferSerifId(object) { if ...

Can you explain the distinction between postMessage() and dispatchEvent() in relation to the origin policy?

Here is some code that I wrote. I tried setting the MessageEvent's origin to *, but I'm still getting an error in the console saying "Blocked a frame with origin "AAAA" from accessing a frame with origin "BBBB". Protocols, domains, and ports must ...

Selecting tabs in Angular with a controller function

I'm currently working on implementing AngularJS to show the tab number when a specific tab is selected using the controller method. However, it's not working as expected. Any assistance on this issue would be greatly appreciated. HTML <body ...

What is the process for entering a value into mysql based on the date?

Seeking assistance with a specific coding challenge. The task at hand involves inputting a date, such as '2018-05-08', and based on the user's input, storing the value in different columns of a database table. For instance, if the date is &a ...

Sign up for a new magazine or newsletter once your current one has been fully processed | React-Meteor

Currently, I am working with two publications: teams.dashboard and boards.board. My goal is to load the boards.board publication using the boardId from the first loaded Board, which can be accessed like this: Boards.find().fetch()[0]._id. I'm searchi ...

Integrating a fresh element into the carousel structure will automatically generate a new row within Angular

I'm currently working on an Angular4 application that features a carousel displaying products, their names, and prices. At the moment, there are 6 products organized into two rows of 3 each. The carousel includes buttons to navigate left or right to d ...

Error occurs when JSON.parse is used

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var data = "{ 'name': 'John' }"; var result = JSON.parse(data); </script> ...

Unable to execute $http in AngularJS Plunker

Having trouble running $http on the Plunker. Can you please review my code and assist me? var QuizApp = angular.module('QuizApp', []); QuizApp.controller('QuizController', ['$scope','$http',function($scope,$http) { ...

SweetAlert.js does not function properly within a custom AngularJS directive

When creating a list to display in a modal, I utilized directives for the modal implementation. (I actually didn't write these directives myself) Within the list, each item features two buttons - one for editing the name and the other for deleting t ...

Navigating Error: net::ERR_CONNECTION while utilizing Puppeteer

I attempted to utilize a proxy from the following site: Below is my Puppeteer scraping code (deployed on Heroku), encountering an error at the .goto() method, as mentioned in the title: const preparePageForTests = async (page) => { const userAgent = & ...