Timing problem in AngularJS service when sharing data with components on a single page

I am encountering an issue while using multiple components on a composite page and trying to reference data from a common service. The main problem arises when I attempt to create the object in the service within the first component and then access it in the second component; if the second component is placed before the first one, the value object has not been instantiated yet causing the second component to fail to display anything.

Although I hoped that two-way data binding would resolve this issue, unfortunately, it did not.

Composite HTML

<second-component></second-component>
<first-component></first-component>

First Component

angular.
module('simple').
component('firstComponent', {
    template: "<h3>Component 1</h3><ul ng-repeat='val in $ctrl.someVals'><li>{{val}}</li></ul>",
    controller: function(factory) {
        'use strict';
        // Responsible for creating an object in the service
        factory.changeData();
        this.someVals = factory.vals;
    }
});

Second Component

angular.
module('simple').
component('secondComponent', {
    template: "<h3>Component 2</h3><ul ng-repeat='val in $ctrl.someVals'><li>{{val}}</li></ul>",
    controller: function(factory) {
        'use strict';
        // As a sub-component, secondComponent depends on an object being present in the service. This
        // will be created by firstComponent, which will reside on the same page.           
        this.someVals = factory.vals;
    }
});

Factory Service

angular.
module('simple').
factory('factory', function() {
    var data = {};
    data.vals = {};
    data.changeData = function() {
        data.vals = {
            "a": 11,
            "b": 22,
            "c": 33
        };
    };
    return data;
});

I expect both component 2 and component 1 to reference the same data after it has been modified by component 1:

Component 2

  • 11
  • 22
  • 33

Component 1

  • 11
  • 22
  • 33

However, what actually happens is:

Component 2

Component 1

  • 11
  • 22
  • 33

I am looking for a solution to instantiate objects in one component and share them with another component without worrying about their order on the page. In this scenario, timing plays a crucial role. Reversing the order of the components works fine, but visually I need my second component to come first. Instantiating the object in the service from the second component does not make sense as it should only rely on service state data without modifying it directly. Despite my initial belief, two-way data binding does not behave as expected when the first component alters the object in the service.

P.S. I am new to AngularJS. Any recommendations for reference materials or tutorials would be greatly appreciated!

Answer №1

To meet your specific requirements, you will need to trigger the service call again. You can utilize $emit to send a message from the first component to the second component and consequently invoke the service function once more. First Component

factory.changeData();
notify();
this.someVals = factory.vals;
function notify(){
 $rootScope.$broadcast('notifier', message);
}

Second Component

function updateVals() {
 this.someVals = factory.vals;
}
$scope.$on('notifier', updateVals)

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

It seems like I'm having trouble sharing a collection of objects

Hey there, here's where I currently stand. I've got some code that sends an array of items to a .NET WebAPI (c#). var stuff = []; $('#items').find('input').each(function(){ var text = $(this).val(); stuff.push({ ID: ...

Angular: Refresh mat-table with updated data array after applying filter

I have implemented a filter function in my Angular project to display only specific data in a mat-table based on the filter criteria. Within my mat-table, I am providing an array of objects to populate the table. The filtering function I have created loo ...

What initiates Electron after npm processes the package.json file?

As I delve into the realms of JavaScript, HTML, and Electron, a particular question has been playing on my mind - what exactly happens when you run electron . in the "scripts" -> "start" section of package.json? The mysterious way it operates sends shiv ...

What is preventing me from implementing my JavaScript event on my EJS code?

Looking to add a click event to the image in my EJS file, here's the EJS code snippet: <div class="container" id="comments"> <div class="row"> <div class="col-lg-12"> <div class="well"> ...

Using JQuery's change function with a Button Group is a great way

I encountered an issue where my button group works with the on.click function but not with on.change. <div class="ui buttons"> <button class="ui button">Value 1</button> <button class="ui bu ...

Troubleshooting React on an Apache Server: A Comprehensive Guide

An interactive React application utilizing React Router has been successfully deployed on an Apache server. After making modifications to the .htaccess file, most of the routes function correctly as intended. Some specific routes within the app rely on us ...

Send backspace key press event to the applet and prevent it from continuing

I am struggling with a Java applet on my webpage that allows users to edit text. Whenever a user tries to modify the text by pressing the backspace button, the browser mistakenly forwards to the previous page. I attempted to filter out the backspace key pr ...

Whenever a menu option is clicked in Umbraco, the page always redirects to the route #/content

After updating my site to the latest version available, I encountered a problem: Whenever I click on any link in the menu on the admin page (/umbraco) The temporary solution I discovered is Click on the link Go to profile Edit Confirm that you want to ...

The functionality of jQuery.hover with AJAX is malfunctioning

I am facing an issue with my jquery hover combined with $.post method. My initial intention was to create a series of select buttons where hovering would trigger a change in the image being displayed (the image path would be loaded via $.post). The image ...

Leveraging the boolean values of attributes within JSX statements

I have been working on a React.js project where I am trying to incorporate a data-picker plugin that requires a specific style of input-attributes: <input data-enable-time=true /> However, I have encountered an issue where webpack fails to compile t ...

Maintaining an onExit function in the ui-router framework

I am trying to implement an animation on an element within a page when the user is transitioning out of a state. Here is my current code snippet: { ....., views: { ... }, onExit: function(){ someEle.classList.remove("someClass"); // ...

What is the best way to retrieve the HTML output generated by AngularJS?

Is there a way to access the rendered HTML content inside a div and place it within the controller's scope in Angular? I am still learning about directives in Angular but I'm having trouble retrieving the rendered HTML after it is displayed. Any ...

Send a quick message with temporary headers using Express Post

When creating a response for a post request in Express that returns a simple text, I encountered an issue. var express = require('express'); var app = express(); var bodyParser = require("body-parser"); var multer = require('multer') ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...

Obtain the URL for making an asynchronous request using PHP and SQL

I'm encountering some issues with a website I am attempting to update. A script named "jquery.script.js" is called in the head section containing some code. $.ajax({ url: 'function.js.php?option=urlget&id='+movie_id, ...

I must first log a variable using console.log, then execute a function on the same line, followed by logging the variable again

Essentially, I have a variable called c1 that is assigned a random hexadecimal value. After printing this to the console, I want to print another hex value without creating a new variable (because I'm feeling lazy). Instead, I intend to achieve this t ...

What is the best way to refrain from utilizing the && logical operator within the mapStateToProps function in Redux?

When I'm trying to access a nested state in a selector, I often find myself having to use the && logical operators. const mapStateToProps = store => ({ image: store.auth.user && store.auth.user.photoURL; }); If I don't use ...

The specified column `EventChart.åå` is not found within the existing database

I've been developing a dashboard application using Prisma, Next.js, and supabase. Recently, I encountered an issue when making a GET request. Prisma throws an error mentioning a column EventChart.åå, with a strange alphabet "åå" that I haven&apos ...

CKEditor's height automatically increases as the user types

I am using a ckEditor and looking for a way to make its height automatically grow as I type. https://i.stack.imgur.com/m7eyi.png <textarea name="description" id="description"> </textarea> <script> CKEDITOR.replace( 'description ...

What is the reason behind only the initial option showing up in the selection when utilizing ng-options?

When using ng-repeat to populate a select element and adding two options below it, only the first option appears. What could be causing this issue? For example: <select id="dropDownSelect", ng-model="chosenDash.id", ng-options="dashboard._id as ...