컨트롤러, 지시문 등에서 동적 데이터를 공유하도록 서비스가 필요한 경우 어떤 패턴을 사용해야하는지 알고 싶습니다. 동적이라고 언급 한 이유는 ' 새로운 데이터를로드하려는 경우이 데이터는 다른 컨트롤러, 지시문 등에서 사용할 수 있어야합니다. 예를 들어 지시문이 UL LI를 생성하는 경우 서비스 내의 데이터가 변경된 경우 지침을 다시 생성해야합니다.공유 방법 컨트롤러 및 지시문 간의 서비스 동적 데이터
나는 처음에 다음을 열었습니다. (How to create reset() method in Service that return promise?) 누군가 제가 옵서버 패턴을 사용해야한다고 지적했습니다. 나는 매우 감사 그리고 난 의견이 매우 나는이 내 대부분의 문제를 해결할 것이라고 생각
var MyApp = angular.module('MyApp', []);
MyApp.config(function($locationProvider){
$locationProvider.hashPrefix('!');
});
MyApp.factory('MyService', function($timeout){
var data;
var loadData = function(){
data = {
foo: "bar",
time: new Date()
};
return data;
};
return {
refresh: function(){
loadData();
},
getData: function(){
return loadData();
}
};
});
MyApp.controller('MyCtrl', function($scope,MyService,$timeout){
$scope.foo = "Service share data";
$scope.data = MyService.getData();
$scope.$on("eventFoo", function(){
console.log("Data has changed!");
console.log($scope.data);
});
$timeout(function(){
MyService.refresh();
$scope.$apply(function(){
$scope.data = MyService.getData();
$scope.$emit("eventFoo");
});
}, 3000);
});
MyApp.directive('myDirective', function(MyService,$timeout){
return {
restrict: 'A',
link: function(scope, elem, attrs){
scope.$on("eventFoo", function(){
console.log("Event foo triggered!");
scope.data = MyService.getData();
console.log(scope.data);
});
}
};
});
을 감상 할 수있다 내가하고 필요의 스파이크로 매우 빠르게 쓴하지만 거기에 뭔가 것을 기억이 필요해. 로드 할 데이터는 $ http GET에서 가져온 것이므로 데이터를 업데이트하거나로드 한 다음 올바른 이벤트를 트리거해야 할 때마다 적어도 약속을 사용해야한다고 생각합니다.
AngularJs에 대한 경험이 부족하여 제 생각에는 의문이 생겨 어떤 도움이나 조언도 매우 만족 스럽습니다!
감사합니다.