2014-05-12 3 views
0

저는 AngularJS에 대해 매우 익숙합니다. 그래서 저는 여전히 JQuery와 기본 자바 스크립트 방식으로 고심하고 있습니다.지시어와 컨트롤러간에 데이터를 공유하는 적절한 방법은 무엇입니까

나는 3 개의 컨트롤러와 사용자 지정 지시문이있는 응용 프로그램을 가지고 있으며 지시문이 자신의 부모가 아닌 다른 컨트롤러에 일부 데이터를 가져 오도록 알리고 싶습니다.

나는 데이터를 포함하는 변수, getter 및 setter 함수 및 업데이트 할시기에 대한 내 컨트롤러에서 토글 및 감시하는 변수가있는 솔루션을 생각해 냈습니다.

myApp.service('sharedService', function() { 
this.update = false; 
this.data = []; 

this.toggleUpdate = function(){ 
    if(this.update === false){ 
     this.update = true; 
    } 
    else { 
     this.update = false; 
    } 
}; 

this.getData = function() { 
     return this.data; 
}; 

this.setData = function(value) { 
    this.data = value; 
}; 
}); 

나는 단지 sharedService.toggleUpdate()를 호출합니다. 컨트롤러가 리소스에서 새 데이터를 가져 오길 원할 때. 내 컨트롤러는 $ scope. $ watch를 사용하여 내 서비스의 업데이트에 대한 변경 사항을 감시합니다.

myApp.controller('PlanController', ['$scope', 'sharedService', function($scope, sharedService){ 

     $scope.init = function(){ 
      //fetch data from API 
     } 

     //watch for toogling the new data 
     $scope.$watch(function() { 
      return sharedProps.update; 
     }, function(newVal, oldVal) { 
      $scope.init(); 
     }, true); 
    }); 

나는 그림을 얻길 희망합니다.이 작업을 수행하는 적절한 방법입니까, 아니면 더 쉬운 방법이없는 것입니까?

myApp.service('sharedService', function ($rootScope) { 

    this.update = false; 
    this.data = []; 

    this.toggleUpdate = function() { 
     this.update = !this.update; 
    }; 

    this.getData = function() { 
     return this.data; 
    }; 

    this.setData = function(value) { 
     this.data = value; 
     // The data has been set so let's let everyone know 
     $rootScope.$broadcast('dataSet'); 
    }; 
}); 

컨트롤러 :

+0

나는 당신이 찾고있는 것이 stackoverflow (틀렸다면 올바른 부분)의 또 다른 절인 코드 리뷰라고 생각한다. 질문에 대답하기 위해 서비스는 앱에서 기능을 공유하는 좋은 방법입니다. 다른 방법은'$ emit/$ broadcast'를 사용하는 것인데, 여러 컨트롤러에서 서로 다른 작업을 동기화하려고 할 때 더 많이 사용합니다. '$ watch'는 값 비싼 방법이지만, 나는 그것을 할 다른 방법을 찾으려고 노력할 것입니다 ($ 브로드 캐스트가 할 것입니다). 내 2 센트 .. –

+0

안녕하세요 알렉스 난 정확히 코드 검토를 찾고 아니에요. 나는 그 통보를 올바르게하는 법을 알고 싶다. 나는 너의 생각이 나를 위해 일한다고 생각해. 수락 할 수 있도록 답을 게시 해주세요. –

답변

1

좋아, 그래서 여기에 내가 정확한 요구 사항에 대한 확실하지 않다, 내 대답이다 : 그 s의 경우

myApp.service('sharedService', [ '$rootScope', function ($rootScope) { 
    this.update = false; 
    this.data = []; 

    this.toggleUpdate = function(){ 

    this.update = !this.update; 
    if(this.update===true){ 
     this.setData(); 
     $rootScope.$broadcast('onDataSet'); 
    } 
    }; 

    this.getData = function() { 
    return this.data; 
    }; 

    this.setData = function(value) { 
    this.data = value; 
    }; 
}]); 

myApp.controller('PlanController', ['$rootScope', '$scope', 'sharedService', function($rootScope, $scope, sharedService){ 

    $scope.init = function(){ 
     //fetch data from API 
    } 

    // Each controller would have this, rather than the $watch 
    $rootScope.$on('onDataSet', function() { 
     // Shared Service has been updated so let's get the data 
     $scope.myObj = sharedService.getData(); 
    })  
}); 

가 알려줘 어떤 네가 원해.

1

@alexc 내가 무엇을 할 것이라고 제안하고, 여기에 예입니다 이것이 당신이 대답을 게시하고 받아들이 @alexc 문의하시기 바랍니다 위해 작동하는 경우

myApp.controller('PlanController', ['$rootScope', '$scope', 'sharedService', function($rootScope, $scope, sharedService){ 

    $scope.init = function(){ 
     //fetch data from API 
    } 

    // Each controller would have this, rather than the $watch 
    $rootScope.$on('dataSet', function() { 
     // Shared Service has been updated so let's get the data 
     $scope.myObj = sharedService.getData(); 
    })  
}); 

자신의 . 아래의 대답은 문제의 내 이해 그래서

Here is a good little page to visit to get more information

+0

나는 rootscope를 사용하는 것이 나쁜 습관이라고 읽었습니다. –

+0

이 경우가 아니라면, 여러분이 읽고있는 대부분의 것은'$ rootScope'를 조작하는 것에 관한 것입니다. '$ rootScope.var = 0;'과 같이 값을 저장하는 것을 의미합니다. '$ rootScope'에 이미 제공된 함수를 사용할 수 있습니다. – jnthnjns

+0

참고 :'$ scope. $ broadcast'도 있지만 부모/자식 범위 관계에 따라 다릅니다. 여러 개의'$ scope '이있을 수 있지만 오직 하나 ('1)'$ rootScope' <- 이것이'$ rootScope'를 조작하는 것이 나쁜 습관 인 이유입니다 – jnthnjns

관련 문제