Having trouble transferring data between controllers using a service

I have developed a data service to facilitate communication between two controllers, but it seems like there is an issue with its functionality.

Below is the code for the service:

app.factory('SubmitService', function($rootScope) {
    var data = {};

    data.prepForBroadcast = function(recvData) {
        data = recvData;
        this.broadcastItem();
    };

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

    return data;
});

The purpose of this service is simple - it is meant to pass an object between controllers. The following are the functions that are responsible for utilizing this service in my controllers:

In the controller where data is being sent (typically from a form):

$scope.submit = function() {
    submitService.prepForBroadcast($scope.formData);
}

In the controller where data is received and manages a list of items:

$scope.$on('SubmitService', function() {
    this.sampleItems.push(submitService.data);
});

To trigger the submit function, I simply call it from a button using ng-click:

<button class="btn btn-primary" style="height:35px;width:100px;float:right;" id="submit"
    ng-disabled="isDisabled()" ng-click="submit()">
    Submit
</button>

UPDATE 2: Provided below is the receiving controller along with a snippet of its test array:

app.controller('noteController', ['$scope', 'SubmitService', function($scope, submitService) {

    $scope.$on('handleBroadcast', function() {
        this.sampleItems.push(submitService.data);
    });

this.sampleItems = [{
    "title":"Sample Note",
    "text":"This is just a sample text to test out how this works. Example example example!!!",
    "date": new Date()
},
// more examples that aren't relevant

I suspect there may be an issue with accessing my array. Can someone help me identify the root cause? I'm still relatively new to JavaScript.

Answer №1

To ensure array modification works correctly, be sure to reference the appropriate object in the event handler.

var self = this;
$scope.$on('handleBroadcast', function() {
    self.pruebaNota.push(submitService.data);
});

Important: The factory you're using seems a bit messy. It functions, but it's structured in a rather unconventional way.

app.factory('SubmitService', function($rootScope) {
    //ok: define a variable that will be returned and later injected into controllers
    var data = {};

   //ok: add functions to the object being returned
    data.prepForBroadcast = function(recvData) {
  //not evident: replace the variable accessible in closure with a new object
  //if you try to modify existing data here instead of reassignment
  //it will ruin the service injected to controllers
        data = recvData;
        this.broadcastItem();
    };
   ...
    return data;
});

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

What steps should be taken in PHP to display a popup when the user input is found to be invalid?

I've been working on implementing a popup in PHP to show if the user enters an existing username, as per our teacher's requirement to use popUp instead of alert. I have set the visibility property of the popup to "Hidden" in CSS; <div class=&q ...

jQuery if statement appears to be malfunctioning

When the condition operates alone, everything works fine. However, when I introduce an 'and' operation, it does not function correctly. If only one of them is true, the code works. It also successfully takes input values. <!DOCTYPE HTML Code ...

Is there a way to switch from a tab that is being called to the tab that made the call

Imagine you're using a cutting-edge tabbed browser. If you have a page open in one tab that links to another page in a different tab What's the best way to switch from the second tab back to the first tab? Is there an easy way to return to ...

Simulation of N-bodies in three.js

I am attempting to create a project similar to , but I am encountering issues with my system. Can someone assist me? Here is the link to my project: . I believe I may be incorrectly calculating the attraction between each particle. The main problem lies i ...

Leveraging Next.js ISR to pass extra information to the getStaticProps function from the getStaticPaths

Inside SingleBlogPost.jsx, the code for generating blog pages by their slug is as follows: export async function getStaticPaths() { const res = await fetch("http://localhost:1337/api/posts"); let { data } = await res.json(); const paths = data.map(( ...

Stopping the onkeypress event after altering focus

I have a form where my users are asking for the ability to move focus to the next field when the enter key is pressed, instead of submitting the form. To achieve this, I have implemented an onkeypress event handler on the text input field to change the foc ...

Fixed header design with CSS Bootstrap

Can a table be created in bootstrap with fixed headers and scrollable content similar to the example shown here? Is it possible for columns to adjust their size based on the content they contain (wider or narrower)? Also, is it possible to have a horizon ...

Discuss the significance of using require('.') in a Node.js environment

During my exploration of a node.js CLI module documentation, I came across a peculiar line. It involved including external modules in a specific way - using the '.' symbol during the process. While I am familiar with how to include external modul ...

Attempting to devise a jQuery algorithm sorting method

To enhance the answer provided in this post: How to stack divs without spaces and maintain order on smaller screens using Bootstrap I've been exploring ways to develop a jQuery script that dynamically adjusts the margin-top of div elements based on t ...

Concealing an item in an Angular Ionic repeater

I am creating a customizable list control where users can filter through different data levels. This list control consists of 4 hierarchical levels with numerous items. Initially, only the first level item is displayed. Upon clicking on the first level, th ...

Press the button to display all entries in my Angular list

Upon clicking this button, the data should be loaded and displayed in a list. I am utilizing the ng-click and ng-repeat functionalities. I seem to be struggling with how to properly declare the functions within the script. Can someone advise me on the cor ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

NestJS Validation Pipes: Which is recommended - using @UsePipes(ValidationPipe) or @UsePipes(new ValidationPipe())?

While going through NestJS tutorials, I came across two different syntaxes for the UsePipes Decorator: @UsePipes(ValidationPipe) @UsePipes(new ValidationPipe()) Based on my understanding, ValidationPipe is a standalone class, and when using new Validatio ...

A fatal error has occurred in Node as it is unable to set headers after

Just getting started with nodeJs and I'm attempting to read a file from the system. It seems like I can view the file content in the console, but for some reason it's not displaying in the browser. Any ideas what I might be overlooking? var myD ...

The repository's dependencies remain unresolved by Nest

I encountered an error in my nestjs application. Unfortunately, I am having trouble identifying the issue within my code snippet. Here is a glimpse of the relevant sections: AppModule import { Module } from '@nestjs/common'; import { TypeOrmMod ...

How can the border of the select element be removed when it is active in select2

After examining the CSS code, I am still unable to locate the specific property that is being applied to the main element. I am currently customizing the select2 library to suit my needs. However, I am stuck in the CSS as I cannot determine which property ...

How can I nest templates within <pre> elements in Angular?

Is there a way to use ng-include within a 'pre' tag? I have a website with code blocks, some of which have common code that I want to move to a separate partial. For example: <pre> My page-specific code.... <ng-include src="&apo ...

Encountering a problem with the persistent JavaScript script

I have implemented a plugin/code from on my website: Upon visiting my website and scrolling down, you will notice that the right hand sidebar also scrolls seamlessly. However, when at the top of the screen, clicking on any links becomes impossible unless ...

Is there a way for me to determine the exact coordinates of all buttons on a given webpage?

I came across this piece of code, but I'm a bit unsure about where exactly I should input it and how to adjust it to locate the position of each button. Additionally, I'm curious as to where the results (coordinates) will be shown? function find ...

Creating TypeScript Classes - Defining a Collection of Objects as a Class Property

I'm trying to figure out the best approach for declaring an array of objects as a property in TypeScript when defining a class. I need this for a form that will contain an unspecified number of checkboxes in an Angular Template-Driven form. Should I ...