2013-08-12 3 views
1

컨트롤러간에 비동기 데이터의 "변경 사항을 바인딩"하고 싶습니다.각도 : 컨트롤러간에 비동기 서비스 데이터 공유

아마도 조금 혼란 스럽 겠지만 뭔가 가능할 수 있기를 바랍니다. 내가 입력 뭔가를 작성하는 경우 다음과 같은 예에서

, 그것은 잘 작동 : http://jsfiddle.net/Victa/9NRS9/

HTML :

<div ng-app="myApp"> 
    <div ng-controller="ControllerA"> 
     ControllerA.message = {{message.hello}}<br/> 
     <input type="text" ng-model="message.hello"/> 
    </div> 
    <hr/> 
    <div ng-controller="ControllerB"> 
     ControllerB.message = {{message.hello}}<br/> 
     <input type="text" ng-model="message.hello"/>  
    </div> 
</div> 

JS :

angular.module('myApp', []) 
    .factory('myService', function($q, $timeout) { 
     var message = { 
      hello: 'hello world' 
     }; 
     return { 
      getMessage : function(){ 
       return message; 
      } 
     }; 
    }) 

function ControllerA($scope, myService) { 
    $scope.message = myService.getMessage(); 
} 

function ControllerB($scope, myService) { 
    $scope.message = myService.getMessage(); 
} 

하지만 서버에서 내 데이터를 가져옵니다. 위의 예와 같이 데이터를 "링크"하고 싶습니다. http://jsfiddle.net/Victa/j3KJj/

"$ broadcast"/ "$ on"을 사용하거나 $ rootScope에서 객체를 공유하는 것을 피하고 싶습니다.

HTML :

<div ng-app="myApp"> 
    <div ng-controller="ControllerA"> 
     ControllerA.message = {{message.hello}}<br/> 
     <input type="text" ng-model="message.hello"/> 
    </div> 
    <hr/> 
    <div ng-controller="ControllerB"> 
     ControllerB.message = {{message.hello}}<br/> 
     <input type="text" ng-model="message.hello"/>  
    </div> 
</div> 

JS : 당신의 도움에 대한

angular.module('myApp', []) 
    .factory('myService', function($q, $timeout) { 
     var message = {}; 
     return { 
      getMessage : function(){ 
       var deferred = $q.defer(); 

       $timeout(function() { 
        message.hello = 'Hello world!'; 
        deferred.resolve(message); 
       }, 2000); 

       return deferred.promise; 
      } 
     }; 
    }) 

function ControllerA($scope, myService) { 
    $scope.message = myService.getMessage(); 
} 

function ControllerB($scope, myService) { 
    $scope.message = myService.getMessage(); 
} 

감사합니다.

빅터

+0

내 대답은 어디에 있습니까 ?? 나는 이미 그것에 대답했다고 생각했다. – zsong

+0

@ sza 귀하의 도움을 주셨습니다 만, rootScope 또는 $ broadcast/$ on을 사용하는 것은 대규모 어플리케이션에서 쉽지 않습니다. – Vic

답변

1

당신이 a를 factory의 반환 객체의 promise 아닌 실제 객체 자체를 반환한다. 약속 구체적인 객체가 $scope.message

예에 할당 수선하는 그래서 범위에 실제로 기다려야한다 : 나는 당신의 해답이 될 수있는 무언가로 바이올린을 변경

function ControllerA($scope, myService) { 
    myService.getMessage().then(function(obj){ 
       $scope.message=obj 
      }); 
} 

this 바이올린을 참조

+0

굉장 해요, 바보 같아요 .--) 당신 도움을 청합니다. – Vic

+1

이 방법은 단지 내가 사용할 수 있다는 것을 명심해야하지만, 당신이 쓸모있는 것만 사용할 수 있습니다. 해당 객체의 일부 속성 –

+0

실제로이 질문에 대답합니까? 이 메시지는 ControllerA의 범위에 대한 메시지 만 업데이트합니까? 두 범위 모두에서 메시지 변수를 어떻게 업데이트합니까? – flyingL123

관련 문제