0

I just started to develop a pretty simple app in Angular JS with a service/factory that holds data that I'm able to push objects to.

I have an array of different people (see html) that you can add as a candidates using the addCandidate() function located in the factory.

My problem is that I want to be able to store people/objects from that array into more than one array, e.g. candidates2 and candidates3 depending on which route/controller is active.

Am I on the right track or should I think completely different?

Factory and controllers:

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

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

  var candidates = [];

  /* I want to fill this array with objects from myCtrl2 */
  var candidates2 = [];

  return{

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

    /* More functions related to Candidates */

  }
});

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

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

});

/* I want to push candidates to candidates2 here */

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

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

});

/* More controllers of same kind */

HTML:

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

1 Answer 1

1

It looks like you want candidates to be different for each controller. In that case, make the factory build an object constructor (similar to a class, but not really) rather than giving the same object every time.

See this plunker for an example. Notice that each controller requests and news it's own Candidate, rather than using a shared Candidate definition.

Sign up to request clarification or add additional context in comments.

2 Comments

That really helped, its just that I want the data in the array to be available throughout different routes (even if you go back to route 1). If i return to route 1 with controller 1 from another route the factory will build a new candidates object with an empty array and print that out instead of the added candidates.
So if I understand, there will be many instances of these array, and each instance needs to persist? I would make one service that handles the Candidate management, and another one that creates and persists these Candidate objects based on a name or something. Then each controller requests the latter service, and requests, by name, the Candidate object that it needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.