[英]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. 我刚刚开始在Angular JS中开发一个带有服务/工厂的非常简单的应用程序,其中包含可以将对象推入的数据。
I have an array of different people (see html) that you can add as a candidates using the addCandidate() function located in the factory. 我有一系列不同的人(请参见html),您可以使用工厂中的addCandidate()函数添加为候选人。
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. 我的问题是,我希望能够将人员/对象从该阵列存储到多个阵列中,例如候选人2和候选人3,具体取决于激活的路由/控制器。
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: 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. 请注意,每个控制器都请求和新闻它自己的候选者,而不是使用共享的候选者定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.