简体   繁体   中英

Angular JS: Store objects from one array to different arrays/services

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, eg 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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM