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