What is the most effective way for AngularJS controllers to communicate with one another?

As I develop a controller, it must interact with another controller. However, I'm uncertain if this is achievable?

HTML:

<div data-ng-app="TestApp">
<div data-ng-controller="menuCtrl">
    <ul>
        <li> <a data-ng-click="Click()">
            Menu1</a>
        </li>
    </ul>
</div>
<div data-ng-controller="pageCtrl">
    <hr/> 
    <button data-ng-click="getText()">GetText</button>
    <br/>
    <strong data-ng-model="boldText"> {{boldText}}</strong>
</div>

JS:

var app = angular.module('TestApp', []);

app.controller('menuCtrl', function ($rootScope, $scope) {
    $scope.Click = function () {
    //???
    };
})
.controller('pageCtrl', function ($rootScope, $scope) {

    $scope.getText = function () {
        $scope.boldText = 'tst';
    };
});

I have fixed the sample on JSfiddle:sample

Answer №1

To easily achieve this functionality, you can use broadcasting in Angular:

var app = angular.module('MyApp', []);

app.controller('menuController', function ($rootScope, $scope) {
    $scope.clickFunction = function () {
        $scope.$broadcast('ButtonClickEvent', {
           someProperty: 'Data to Send' // add any data here
        });

    };
})

.controller('pageController', function ($rootScope, $scope) {

   $scope.getTextContent = function () {
       $scope.boldText = 'example';
   };
   $scope.$on('ButtonClickEvent', function (event, data) {
        console.log(data); // Output the received data
   });
});

Answer №2

Utilizing event broadcasting allows for seamless transfer of values between controllers.

app.controller('menuCtrl', function ($rootScope, $scope) {
    $scope.Click = function () {
        var valueToPass = "value";
        $rootScope.$broadcast('eventMenuCtrl', valueToPass);
    };
})
.controller('pageCtrl', function ($rootScope, $scope) {

    $scope.getText = function () {
        $scope.boldText = 'tst';
    };

    $scope.$on('eventMenuCtrl', function(event, value) {
        $scope.boldText = value;
    })
});

http://jsfiddle.net/q2yn9jqv/4/

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 Angular's ngOnChanges failing to detect any changes?

Within one component, I have a dropdown list. Whenever the value of the dropdown changes, I am attempting to detect this change in value in another component. However, I am encountering an unusual issue. Sometimes, changing the dropdown value triggers the ...

Modify the styling of the initial picture in a Google Drive file

Having an issue.. I am working on a website where each page is managed through Google Drive. I need to change the CSS styling of only the first image on one specific page. Using :first-child won't work because the HTML structure contains "p > span ...

Is there a way to effortlessly refresh the WooCommerce cart and receive updated HTML content all in one go?

I am currently working on a customized "mini-cart" that mimics the functionality of the main cart page, including options to adjust quantity, remove items, enter coupons, and remove coupons. I have set up the cart to submit changes via Ajax by listening fo ...

Displaying separate items onto a webpage based on their unique identifiers

Currently, I am in the process of developing a JavaScript web application that retrieves input from a user (specifically the name of a music artist) and then produces a list of related artists along with their most popular songs, all thanks to information ...

Node-powered Angular

Currently working on setting up client-side routing with AngularJS and Node. Ran into some issues along the way. EDIT After making changes to my code based on recommendations from @PareshGami, following https://github.com/scotch-io/starter-node-angular, I ...

What is the best way to apply index-based filtering in Angular JS?

I am working on a tab system using ng-repeat to display tabs and content, but I'm facing some challenges in making it work seamlessly. Below are the tabs being generated: <ul class="job-title-list"> <li ng-repeat="tab in tabBlocks"> ...

Leverage Firebase and AngularJS to manage the process of verifying email

Currently, my web app utilizes Firebase and AngularJS. I have a factory that is used across all modules in my app: .factory('Auth', ["$firebaseAuth", function($firebaseAuth) { return $firebaseAuth(); } ]); Ensuring authentication ...

Enhance Your Website with GatsbyJS Custom Scrollbars

I'm struggling to customize the default scrollbar on my Gatsby website with an overlay scrollbar. I want to avoid the page 'shifting' slightly to the left when switching between pages that have scrollbars and those that do not. My attempt i ...

Sprockets could not locate the file for jquery.atwho

I have been attempting to integrate the jquery-atwho-rails into my application, a Rails gem designed for at.js. I have followed all the steps provided, executed bundle install, included the necessary code in both application.js and application.css, stopped ...

In React hooks, Socket.io has a strange behavior where it adds users multiple times with varying socket IDs

Encountering an issue with my React and Socket.IO application. Upon a user joining a room, their information is being duplicated in the client's array on the client side. Despite having the same username, the entries have different socket IDs assigned ...

What are the steps for implementing if-else statements in JavaScript when working with multiple dropdown lists?

I have encountered an issue while trying to display options in multiple drop-down lists. Only two words (CHENNAI AND IOS-XE, BANGALORE AND IOS-XR) are being displayed and the rest of the words are not appearing. Can someone provide assistance on fixing thi ...

What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API: const attractions = [ {"id": 1,"name": "drive on avenue"}, {"id": 2, "name": "diving"}, {"id": 3,"name": "visiting ma ...

There appears to be an inexplicable issue hindering the functionality of smoothscroll in

Continuing to improve my website: I have implemented a button for scrolling down the page, but I would like to add smooth scrolling functionality for a better user experience. After some research and experimentation, I came across this compact script tha ...

Send the chosen value from a dropdown menu to a PHP script

<style type="text/css"> form select { display:none; } form select.active { display:block; } </style> <script type="text/javascript"> window.onload = function () { var allElem = document. ...

In JavaScript, Identify the filename selected to be attached to the form and provide an alert message if the user chooses the incorrect file

I have a form in HTML that includes an input field for file upload. I am looking to ensure that the selected file matches the desired file name (mcust.csv). If a different file is chosen, I want to trigger a JS error. Below is the form: <form name="up ...

What is the best way to link CSS files from libraries that are downloaded using npm?

For instance, let's say I installed a package: npm install --save package and it gets saved in ./node_modules/package/ Inside that folder, there might be a directory named styles and within that directory, you could find style.css. How can I link ...

Is it possible to pass a PHP array to JavaScript without using Ajax?

Currently, I have a JavaScript function that utilizes Ajax to fetch an array of data from PHP and dynamically populates a dropdown menu. Everything is functioning as expected. However, I am beginning to feel that using Ajax for this task might be a bit ex ...

Struggling to display a collection of items in React

Below is the code snippet : import React, { Component } from 'react'; import axios from 'axios'; import _ from 'lodash'; import Loader from './Loader'; export default class Main extends Component { constructor(p ...

Prevent the use of exponential notation with double numbers in GWT

Is there a way to remove the exponent from a double on the client side in GWT? public double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); //Need code to remove expone ...

Node.js seems to be having trouble with emitting events and catching them

I'm having trouble troubleshooting my code. // emitter.js var EventEmitter = require('events').EventEmitter; var util = require('util'); function Loadfun(param1, param2, db){ function __error(error, row){ if(error){ ...