Reputation: 107
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>
Upvotes: 0
Views: 3323
Reputation: 2929
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.
Upvotes: 1