2017-05-12 7 views
0

:각도 통신 나는 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 
     } 
    } 
}); 
+1

언제든지 이벤트 알림을 사용하여 통신 할 수 있습니다. 예를 들어 이벤트를 "구독"하고 "브로드 캐스트"할 수있는 여러 서비스가 있습니다. 그래서 하나의 서비스 또는 컨트롤러와 다른 서비스 또는 컨트롤러가 듣고있는 특정 이벤트를 브로드 캐스트합니다. – Scott

답변

1

서비스 및 공장은 싱글 톤입니다. 그 주위에는 방법이 없습니다 (각도 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 
}