Sharing information between controllers from diverse modules

We are currently in the process of developing a Telecom App dashboard. Our goal is to retrieve logs using Logstash and Elastic search, and then present them on the UI using the ng-Table directive of Angularjs.

While we have successfully obtained the logs, we are facing an issue with sending the response between two controllers from different modules.

Below is the code snippet:

Code for retrieving logs from Elastic search:

// Creating EsConnector module which depends on the elasticsearch module
var EsConnector = angular.module('EsConnector', ['elasticsearch']);

// Creating the es service using esFactory
EsConnector.service('es', function (esFactory) {
  return esFactory({ host: 'localhost:9200' });
});

// Defining an Angular controller to check server health
EsConnector.controller('ServerHealthController', function($scope, es) {
es.cluster.health(function (err, resp) {
        if (err) {
        $scope.data = err.message;
    } else {
        $scope.data = resp;
   }
});
});

// Defining an Angular controller to fetch query results
EsConnector.controller('QueryController', function($scope, es) {
// Searching for documents
    es.search({
    index: 'logstash-2014.08.29',
    size: 500,
    body: {
    "query":
        {
            "match": {
                "CallId":-1            }   
        },
    }      
    }).then(function (response) {
      $scope.hits = response.hits.hits;
    });

});

We are looking for a way to pass the data (i.e., hits obtained from QueryController in EsConnector module) to MainController in the app module.

Here is the app module:

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

app.controller('MainController', function($scope, ngTableParams){
 $scope.query = {} 
 $scope.queryBy = '$'
 var data = ; \\ We want to populate 'data' with 'hits' from QueryController
  $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 10           // count per page
    }, {
        total: data.length, // length of data
        getData: function($defer, params) {
        $defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
    }
});

Approaching the situation could involve merging both modules.

Thank you.

Answer №1

There are various ways to achieve this, but the most efficient method, in terms of code separation, would be through events.

If the modules are loaded on the same page, they are likely children of $rootScope, allowing you to use events to communicate information ($rootScope.$on('myEvent', function (data){}) - $rootScope.$emit('myEvent', {...}).

An alternative, though less clean approach, would involve using AngularJS services as data managers to store and retrieve information in different components. The recipient controller could then $watch the response of this service.getLogs() for updates, ensuring it always has access to the most up-to-date data (though this may impact performance).

Additionally, if you need to display specific information as soon as it is received, you can initialize your controller's data model with "$scope.myModel.logs" as null, and use an ng-if condition to display the block that should show this information once myModel.logs is updated (when the event is triggered, the data model will be updated and the block will be shown).

Answer №2

Feel free to explore one of my previous articles -

http://stackoverflow.com/questions/25301581/angular-js-newbie-link-in-a-controller-view-that-triggers-another-controller-a/25305951#25305951

Check out this demonstration I created on Plunker -

http://plnkr.co/edit/1dhdPfmB1WwAkYhsz4Hv

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

Utilizing a single controller in multiple locations within AngularJS

I am currently working on developing an Ionic application which includes screens with lists containing checkboxes and the option to select all items. My experience with AngularJS and Ionic is fairly limited. The "Select All" functionality works as intende ...

Removing an Element in a List Using Jquery

In my JQuery, there is a list named additionalInfo which gets populated using the function below: $('#append').on('click', function () { //validate the area first before proceeding to add information var text = $('#new-email&a ...

Creating custom directives in AngularJS can be a rewarding and powerful

When working with two directives, a situation arose where it was necessary to clear the value in Directive A by using a button located in Directive B. However, when attempting to do this using typical DOM manipulation tools like jQuery, an error occurred w ...

Is it better to use scale.set() or simply increase the size of the model in Three.js?

When it comes to scaling 3D models in Three.js (or any other 3D renderers), what is considered the best practice? Recently, I encountered a situation where I loaded a model only to realize that its size was too small. In order to adjust the size, I used m ...

pass information between sibling directives

I am currently experiencing an issue with an AngularJS directive. I am trying to send an outlet object from directive1 to directive2, both of which share the same controller scope. I have attempted to emit an event from directive1 to the controller, broadc ...

Show a collection of files in a table format

Here is the current code I have: index.html <!DOCTYPE html> <html> ... </form> </div> </body> </html> And here is my code.gs function doGet() { return HtmlService.createHtmlOutputFromFile('index'); } ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

Troubleshooting: Issue with JQuery click functionality within Django's AJAX implementation

I've been tackling the Tango with Django exercises to get a better grip on Django. I'm almost finished, but I'm hitting a snag with the Ajax segment. The Ajax function for auto-adding a page isn't triggering. I can't seem to figur ...

Is it possible to utilize Ajax submit requests within a (function($){...}(jQuery)); block?

As a PHP developer with some knowledge of JavaScript, I am currently using AJAX to send requests to the server. I recently came across the practice of enclosing all code within an anonymous JavaScript function like: (function($){ //code here }(jQuery)). Fo ...

Fluctuate the window.location with jQuery or javascript

My goal is to create a functionality where clicking an image will toggle the window.location url between '#' and '#footer'. The current code I have for this is: <script> function clickarrow(){ var rd=Math.floor(Math.random() ...

What is the best way to update the text on buttons once they've been clicked for a variety of buttons

I'm encountering an issue with multiple buttons where clicking on any button causes the text to change on the first button, rather than the one I actually clicked on. All buttons have the same id, and using different ids for each button seems impracti ...

MongoDB issued an error notification stating: "The operation `disneys.insertOne()` has experienced a timeout after 10000 milliseconds."

I am currently in the process of developing a new API using MongoDB and Express, and I have come across the following issue: "Operation disneys.insertOne() buffering timed out after 10000ms." To test my API, I am using route.rest. However, I ...

Encountering an issue when trying to generate a button in Angular

I am currently using JavaScript to dynamically create a button in Angular. While I have been successful in creating the button, I am encountering an error when attempting to change the classname. The error message I am receiving is: Property 'clas ...

The toggle button requires two clicks to activate

I created a toggle button to display some navigation links on mobile screens, but it requires two clicks upon initial page load. After the first click, however, it functions correctly. How can I ensure that it operates properly from the start? Below is t ...

Define CSS styles based on the content of a specific cell within a table

Is there a way to target a <td> in CSS based on its content value? <table> <tr> <td>Name</td> <td>John</td> <tr> </table> For instance, how can I apply the color:bl ...

Mastering the art of tab scrolling in VueJS using Bootstrap-vue

Currently, I am working on a VueJS project that utilizes bootstrap-vue. The issue I am facing is that when rendering a list of tabs, it exceeds the width of its parent container. To address this problem, I aim to implement a solution involving a set of but ...

How can I make the footer on my webpage have a white background?

My goal is to create a white div that spans from point (A) to point (B) on the page, just like in the image. I aim for it to stretch all the way down to cover the entire browser without showing any gray background underneath, even when the page is scrolled ...

What is the most effective method for postponing the loading of JavaScript?

Incorporating a bootstrap theme into my project has required me to include several javascript files. The challenge arises when some pages load dynamic content from the server, resulting in the entire HTML not being present when the javascript files are exe ...

Angular CLI: Trouble with building in production mode due to errors in "Abstract class" while using Angular 4

Within my app.resolver.service.ts file, I have an Abstract class. During development, everything works fine, but I encounter an error in the PROD build. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/commo ...

Executing multiple child processes in a loop with asynchronous operations and collecting the output after the loop concludes

Here's a snippet of code I've been working on... const { exec } = require('child_process'); const Main = async () => { const result = await RetrieveAllItems(); console.log('output', result); }; const RetrieveAllI ...