我正在学习AngularJS,而我却失去了如何解决看似简单的任务:
我希望有一种控制器和指令对可以在它们之间进行通信,存储和共享数据,但是要与其他类似的控制器/指令保持分开。我想使用角度服务,因为我有很多数据和函数,我想把它放在服务中,而不是在每个控制器中重复自己,但问题是服务是单例;我想要的是同一服务的几个可注入实例。 (或者是实现这一目标的更好的实践替代方案)
这是一个类比
A class is doing a science project about growing plants.
Students are grouped into pairs. (a controller and a directive)
Each pair is assigned a garden (an instance of the service).
Every garden comes with tools + money for seeds (functions + data-fetchers on the service)
The students must be told where their respective gardens are (injecting the service)
One of the students must buy and plant the seeds (the controller)
The other must maintain those seeds via watering and weeding (the directive)
Every pair of students must work independently from other pairs
这是我的代码的大概(目前只有一个单身):
//Garden service
//This is only a single service.
//I want a factory that produces these services, which I can then inject
angular.module('foo').service('garden', function(){
this.seeds = [];
this.buySeeds = function(seedsToBuy) { //go to store };
this.plantSeeds = function (){...};
this.shovel = function(){...};
this.water = function(){...};
this.pesticides = function(){...};
});
//Controller student
angular.module('foo').controller("controllerStudent", function($garden){
garden.buySeeds(['tree', 'cantelope', 'cactus']);
garden.shovel();
garden.plantSeeds();
garden.water();
});
//Directive student
angular.module('foo').directive("directiveStudent", function($garden){
return {
scope: {},
link: function(scope, elem, attrs){
garden.water();
garden.shovel();
garden.pesticides();
//The garden is then presented by rendering it on the elem
}
}
});
答案 0 :(得分:1)
服务和工厂是单身人士。没有办法(除非你想切换到Angular 2)。我也认为你过分思考了一下。
app.factory('GardenFactory', function() {
function Garden() {
this.seeds = [];
this.buySeeds = function(seedsToBuy) { //go to store };
this.plantSeeds = function (){...};
this.shovel = function(){...};
this.water = function(){...};
this.pesticides = function(){...};
}
function newGarden() {
return new Garden();
}
return {
newGarden: newGarden
}
});
现在你有一个生产花园的工厂。您可以从您的控制器创建花园,如果您想将这些花园留在记忆中,您可以将它们添加到您服务的一系列花园中:
// get student ID from route xx.com/students/1
app.controller('StudentCtrl', function(GardenFactory, GardenService, studentId) {
var $ctrl = this;
// find students garden or create new one
$ctrl.garden = GardenService.gardens.find(function(g) {
return g.id == studentId; //conditional to associate garden with student
}
if (!garden) {
$ctrl.garden = GardenFactory.newGarden();
GardenService.gardens.push($ctrl.garden); //semi-persist to service
}
function doStuffToGarden() {
$ctrl.garden.buySeeds(['tree', 'cantelope', 'cactus']);
$ctrl.garden.shovel();
$ctrl.garden.plantSeeds();
$ctrl.garden.water();
}
}
app.service('GardenService', function() {
var GardenService = this;
GardenService.gardens = []; //semi-persistent list of gardens
}