Angular JS: Distribute objects from a single array to various arrays or services

I have recently embarked on developing a basic app using Angular JS, utilizing a service/factory to manage data and enable the addition of objects.

Within the array of various individuals (listed in the html), you can include them as candidates by employing the addCandidate() function within the factory.

My current dilemma involves wanting to store people/objects from that array into multiple arrays such as candidates2 and candidates3, based on the active route/controller.

Do I need to rethink my approach or am I heading in the right direction?

Here are the factory and controllers:

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

app.factory('Candidates', function (){

  var candidates = [];

  /* The aim is to populate this array with objects from myCtrl2 */
  var candidates2 = [];

  return{

    addCandidate: function(candidate){
      candidates.push(candidate);
    }

    /* Additional functions pertaining to Candidates */

  }
});

app.controller('myCtrl1', function($scope, Candidates){

  $scope.addCandidate = function(candidate){
   Candidates.addCandidate(candidate);
  }

});

/* The intention is to transfer candidates to candidates2 here */

app.controller('myCtrl2', function($scope, Candidates){

  $scope.addCandidate = function(candidate2){
   Candidates.addCandidate(candidate2);
  }

});

/* More controllers similar in nature */

The HTML structure for reference:

<ul>
    <li ng-repeat="person in people">
      <h2>{{ person.name }}</h2>
      <button ng-click="addCandidate(person)">Add candidate</button>
    </li>
</ul>

Answer №1

If you're looking to have different candidates for each controller, consider having the factory create an object constructor unique to each controller instead of returning the same object each time.

Take a look at this example on Plunker for reference. You'll see that each controller is able to request and utilize its own Candidate object rather than sharing a single definition.

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

Transmit JSON data to the server using Spring 3.x

I am facing an issue with sending JSON to the server using Spring 3.x. I have tried using the @RequestBody annotation, but it seems that my controller is not getting called. Could someone please provide me with a complete example? I attempted to follow th ...

Maximizing efficiency with JavaScript object reduction

let students = [ { name: "john", marks: 50, }, { name: "mary", marks: 55, }, { name: "peter", marks: 75, }, ]; I need to find the total sum of marks using the reduce method. Here is my att ...

Ways to verify if Arabic text has been submitted by the user through a form?

Is there a foolproof method for detecting Arabic input in a form before submission? Can Javascript effectively manage this task, or is it better handled by server-side scripts like .NET? I propose implementing a script to immediately block users from ente ...

Reorganizing Arrays in Javascript: A How-To Guide

I have an array in JavaScript called var rows. [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f4f2e4f3b0c1e4f9e0ecf1ede4afe2eeec">[email protected]</a>' }, { email: '<a hre ...

What is the reason for the addEventListener function not being able to access global variables?

I have set up an event listener function to utilize popcorn.js for displaying subtitles. Additionally, I have created functions that are unrelated to popcorn.js outside of the event listener and declared a global variable array. However, when attempting ...

Ways to block past dates on bootstrap date picker starting from the current date and how to prevent dates beyond 90 days in the future from being selected on the

I am currently facing an issue with disabling previous dates from the current date in my code. While the functionality works well for the "From Date" date picker, I am having trouble implementing the same restriction for the "To Date" date picker after 90 ...

Tips for Resolving This Issue: Dealing with Cross-Origin Read Blocking (CORB) Preventing Cross-Origin Response

Caution: jquery-1.9.1.js:8526 The Cross-Origin Read Blocking (CORB) feature has blocked a cross-origin response from with MIME type application/json. For more details, refer to . My Code snippet is as follows: <!DOCTYPE html> <html> <hea ...

What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file: There appears to be an error in your GraphQL query: Cannot find field "allNavigationLinksJson" on type "Q ...

How can I update data in Select2 after it has been initialized?

After initializing select2, I am trying to set an array of data in the following way: var selection = $('#selection').select2({}); selection.data([ {id: 1, text: 'value1'}, {id: 1, text: 'value1'} ]); However, I am encou ...

Am I utilizing the htmlspecialchars function properly?

My main objective is to protect the user from malicious code and prevent XSS attacks. I have implemented a series of checks to filter the user's input before storing it in the database. The user input is stored in the $post variable. $post = htmlspec ...

Retrieving JSON data from the XAMPP localhost in Eclipse

I am new to the world of Android development and programming, and I am currently working on an app that will download a JSON feed from the internet and display it on the screen. Since I don't have access to a server, I am utilizing XAMPP. Based on my ...

The POST request to write to a JSON file using fs.fileWrite is malfunctioning and unable to establish a connection with localhost

I am currently facing challenges with expressing myself effectively. My struggle lies in getting a post request to function properly. I aim to use the post request to update an item in a cart.json file, leveraging Node.js's fs.fileRead and fs.fileWrit ...

Steps for including a font ttf file in Next.js

As a newcomer to Nextjs, I am eager to incorporate my own custom fonts into my project. However, I find myself completely bewildered on how to execute this task (my fonts can be found in the "public/fonts/" directory). The contents of my global.css file ar ...

How can I load a .json file into JavaScript without inserting it directly into the code?

Currently, I am dealing with a lengthy JSON snippet that resembles the following: { "section: [ [stuff] ] } To incorporate this into my JavaScript code, I currently use the following approach: var obj = { // {All the stuff from above} } My ...

``Retrieve a specific JSON data object from a file that contains multiple JSON data objects and condense it for

Take this scenario for instance: { "a":1 } { "b":2 } I need to convert it to : {"a":1} {"b":2} Is there a way to achieve this using bash scripting? ...

Extract data from XML CLOB field

Hello there, I am facing an issue with SQL. I have a table with a data type CLOB where a CLOB is stored. In the same table, if we have XML format, we use a function to extract the XML field. CREATE OR REPLACE FUNCTION gettagvalue ( XMLBody IN CLOB, TagXml ...

Using AngularJS with ckEditor for managing multiple instances

My upcoming app will feature drag and drop functionality, as well as the ability to drop a CKEditor into it. I am facing an issue where all instances of the CKEditor created have the same "ng-model". Is there a way to create new instances with unique mode ...

Encountering a 404 Not Found issue while trying to add scripts with Node.js

I am currently working with a node server and an HTML file, where the default route is being directed. server.js /** * Created by Creative Coder on 10/26/2015. */ var express = require('express'); var mysql = require('mysql'); var a ...

When you reach the end of the page, the loadMore function is triggered multiple times

On my webpage, I have a list of profiles that are displayed. When the user reaches the bottom of the page, more data should be loaded through the loadMore function. While the loadMore function itself works correctly, I am facing an issue with the listener. ...

Search for a substring in JSON using Python

Currently, I am faced with the challenge of extracting two pieces of information from a lengthy JSON file using Python 2.7. The structure of the JSON data is as follows: { 'device': [ { 'serial': '00000000762c1d3c&apo ...