What is the best way to ensure changes to an item in a Model array are reflected across different scopes?

I am dealing with a scenario where I have both a parent $scope and a child $scope. When the child view loads, I initiate a GET request to fetch JSON data (an array containing hundreds of objects). This data is then passed to the parent $scope.

Within the child view, I retrieve data from the parent's model in order to create widgets using ng-repeat. Each widget contains data (a select dropdown) as well as an edit button that opens a modal residing in the parent view.


The problem:
My challenge lies in pulling the exact selected object data from the model into the modal. Furthermore, any changes made to this data within the modal should be reflected globally - in both the modal itself and the ng-repeat section in the child view.


In the Parent, I initialize an object to store the Array of Objects:

// Model to contain the items:
var itemsModel = {};

A controller call inside the Child upon view load:

// Inside Child view:
// GET request to retrieve items
ItemFactory.getAllItems(byProduct).then(function(data) {

    // Setting the Parent's Model to the fetched data
    $scope.main.itemsModel = data.data.items;

    // Initializing ng-repeat in the child scope
    vm.items = $scope.main.itemsModel;
    vm.totalItems = $scope.main.itemsModel.length;

});

An example of one part of an object within the returned Array from the GET request:

{
    tag: "kitchen",
    term: "Red",
    item_id: "99312"
}

HTML snippet for the ng-repeat section:

<div ng-repeat="item in child.items" class="col-md-6">

<section class="bg-placeholder" value="{{item.item}}">

    <!-- Function to open the parent scope modal -->
    <a href="" ng-click="child.openTagModal(item.item_id, item.item)">
        <div ng-model="child.itemName" class="tag">
            {{item.item}}
        </div>
    </a>

    <div class="item-dropdown">

        <select ng-model="item.chosenTag"
                ng-change="child.updateTag(item)">

            <option value="companies"
                    ng-selected="{{item.tag == 'kitchen'}}"
                    changed="kitchen">kitchen</option>

            <option value="bedroom"
                    ng-selected="{{item.tag == 'bedroom'}}"
                    changed="bedroom">bedroom</option>
            ...

The function in the Child to open the modal that resides in the Parent:

vm.openItemModal = function(id, item) {

    console.log(id);
    console.log(item);

    $scope.main.itemId = id;
    $scope.main.product = item;

    // Displaying the modal
    $scope.main.modal_item = true;
    $scope.main.modal = true;

HTML code for the modal in the Parent:

<select ng-model="main.tag"
        ng-change="main.updateTag(id, item)"
        class="btn-default">

    <option value="kitchen"
            ng-selected="{{main.tag == 'kitchen'}}"
            changed="kitchen">kitchen</option>

    <option value="bedroom"
            ng-selected="{{main.tag == 'bedroom'}}"
            changed="bedroom">bedroom</option>

Currently, modifying the item tag in the Parent model updates the item data in the Database, but does not affect the data within the Child scope or the ng-repeat.

vm.updateTag = function(id, tag, item) {

    // PUT request to update object data in the Database:
    ItemFactory.updateTag(
        id,
        tag,
        item).then(function(data) {
            console.log(data);
        });
    };
}

UPDATE:
Developed a new Factory service to manage updating the model. However, I still face issues with updating the Child tag scope within the ng-repeat FROM the Parent scope:
How to update model on select inside of ng-repeat?


Answer №1

To address your issue, I propose creating a factory that can be accessed by all controllers.

app.service('sharableService',[ function(){
   this.sharableData = {};
   //getter
   this.getData = function(){
      return this.sharableData;
   }
   //setter
   this.setData = function(value){
      this.sharableData = value;
   }
}]);

Alternatively:

Factory

app.factory('sharableService',[ function(){
   var sharableData = {};
   //getter
   var getData = function(){
      return sharableData;
   }
   //setter
   var setData = function(value){
      sharableData = value;
   }
   //methods are exposed.
   return {
      getData: getData,
      setData: setData
   }
}]);

This sharable service is useful for sharing data between controllers.

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

The Present Landscape of Crossplatform JavaScript Unit and Systems Testing

When working on JavaScript projects, which asynchronous system and unit test framework would be best suited for use in both node.js and web browsers? The ideal testing system should have the capability to run specific tests for node.js and web browsers, a ...

The no-unused-expressions rule is triggered when an assignment or function call is expected

I'm just starting out in full stack development and I'm experimenting with coding to improve my understanding of frontend using React JS and Material UI. While working on this component, I encountered an error in the console at line 75 (this.prop ...

Ensure your mobile device is age 13 or over before proceeding

I am developing a project with Next js. Here, I want to render a component if it is a mobile device. However, if I use the isMobileDevice value in jsx, I get the errors below. import useTranslation from "next-translate/useTranslation"; import isM ...

I am looking to retrieve products based on category alone, category and model together, or simply obtain all products in one go. At the moment, I am utilizing three distinct endpoints

I have 3 endpoints on my backend that fetch products based on certain criteria. I'm considering whether to refactor the logic and combine them into a single endpoint/function. Currently, my routes are structured as follows: router.get('/products& ...

What is the best way to dynamically add a stylesheet using JavaScript/jQuery?

I've been scouring the web for a solution to a particular issue, but so far I'm coming up empty-handed. We're working with Umbraco CMS for a client's website, and it seems we can't insert conditional comments in the <head> se ...

Hide preloader in AngularJS once repeater has completed execution

Is there a way to hide a preloader div only after all data has finished loading in an ng-repeat loop? Check out this interactive example on Plunker: http://plnkr.co/edit/ilgOZzIy2axSi5Iy85C7?p=preview Here is the HTML code: <div ng-co ...

What is the best way to store query responses in global.arrays without overwriting the existing values stored within the array elements of global.arrays?

QUESTION: I am struggling to efficiently assign results of MongoDB queries to global arrays. I attempted to store references to the global arrays in an array so that I could easily assign query results to all of them using a for loop. However, this appro ...

The JavaScript array on its second usage had a length of '0', yet it still contained objects within it

About the Task: This task involves working with two arrays: arrNumber, which is a number array, and arrString, which is a string array. The goal is to create a list of objects using the values from arrNumber, where the object keys are numbers or characte ...

Prior to the image being loaded, the JQuery load() function is triggered

I am facing an issue where I want to change the src attribute of my image and then retrieve the width of the new image. The problem is that the JQuery load() function seems to execute before the image is fully loaded and its width is determined. Any sugges ...

Explore the versatility of AngularJS with different layout designs

Currently, I am working on an AngularJS application that consists of app.js as the main JavaScript file where the app initializes, along with an index.html file that serves as the master page applying to all pages in the app. This index.html is located in ...

How can we implement programming logic for a Threejs Particle System that includes connecting lines between particles

I recently inquired about connecting nearby particles in ThreeJS and managed to create lines between them. However, due to the logic of the particle system, the lines are drawn twice. This behavior is similar to how the original 2D particle system function ...

How can I efficiently handle making 50 API requests simultaneously given the restriction of only 10 calls per second for the Rotten Tomatoes API?

My application needs to make 50 to 100 API calls in a loop, but Rotten Tomatoes has a limit of 10 calls per second. As a result, my requests fail and I get different results each time. How can I effectively make these 50 requests without exceeding the 10 ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Is there a way to interrupt a function in jquery before it completes its execution?

I've created a program that activates a sequence of 5 lights and sounds when a button is clicked, continuously looping through the sequence. There's another button labeled "cancel" to stop the loop midway and reset everything to the initial state ...

Explain the inner workings of the setTimeout() function in JavaScript

My goal is to create a line in my code by placing points according to the line equation and adding a 100 millisecond delay before each point is displayed. However, when I try to run the code, it seems to wait for some time and then displays all the points ...

Animating a 3D object's movement using Gsap.js

Recently, I've been experimenting with modules, three.js, and gsap. I'm attempting to animate a 3D object along a path. I found a solution using "common js" that works well here: https://codepen.io/uiunicorn/pen/zYZoYpV However, when I try to in ...

Tips for Configuring a Nestjs Query Using TypeORM to Retrieve Several Entries

When I send this specific URL from my Angular application: http://localhost:3000/api/skills?category_id=2 The main issue revolves around how to modify the code in order to successfully retrieve all skills with a category_id of 2. It is important to note ...

What could be causing the unexpected behavior in my NgMessages form validation?

I have developed a code that incorporates Angular JS form validation methods. There are two separate forms within the codebase, The initial form utilizes basic form validation while the second form employs ng-messages, However, an issue has arisen wher ...

Clicking on a Vue.js element does not trigger the function when an <a> link is present

I am attempting to create a notification system where clicking on the notification and accessing its link will result in a decrease in the total number of notifications.<li class="header">You have {{ notificationsCount() }} notifications</li> & ...

Solving templateUrl resolution of directives in Angular with RequireJS

Currently, I am using AngularJS and RequireJS in my single-page application (SPA). To organize imports efficiently, I rely on RequireJS. With RequireJS, I can utilize features like baseUrl to resolve import paths seamlessly. Now, I wish to apply the same r ...