2012-04-16 3 views
55

모델 콜백에서 모델을 업데이트 할 때 모델 속성을 업데이트해도 영향을 미치지 않습니다.AngularJS에서보기가 업데이트되지 않았습니다.

angular.service('Channel', function() {   
    var channel = null; 

    return {   
     init: function(channelId, clientId) { 
      var that = this;   

      channel = new goog.appengine.Channel(channelId); 
      var socket = channel.open(); 

      socket.onmessage = function(msg) { 
       var args = eval(msg.data);    
       that.publish(args[0], args[1]); 
      }; 
     }  
    }; 
}); 

publish() 기능은 컨트롤러에 동적으로 추가되었습니다

내 서비스입니다.

컨트롤러 :

App.Controllers.ParticipantsController = function($xhr, $channel) { 
    var self = this; 

    self.participants = [];  

    // here publish function is added to service 
    mediator.installTo($channel); 

    // subscribe was also added with publish   
    $channel.subscribe('+p', function(name) { 
     self.add(name);  
    });     

    self.add = function(name) {  
     self.participants.push({ name: name });  
    } 
}; 

App.Controllers.ParticipantsController.$inject = ['$xhr', 'Channel']; 

보기 :

<div ng:controller="App.Controllers.ParticipantsController">  
    <ul> 
     <li ng:repeat="participant in participants"><label ng:bind="participant.name"></label></li> 
    </ul> 

    <button ng:click="add('test')">add</button> 
</div> 

그래서 문제 버튼을 클릭하면 제대로보기를 업데이트하지만 나는 채널의 속삭임에서 메시지를받을 때 심지어는 add() 일이다 함수는

답변

126

이라고합니다. $scope.$apply()가 누락되었습니다.

각도 세계 외부에서 무엇이든 만질 때마다 각도를 알리려면 $apply으로 전화해야합니다. 그건에서 할 수 있습니다 (지침에 의해 처리) ($ HTTP 서비스에 의해 처리)

  • XHR 콜백
  • setTimeout 콜백 ($defer 서비스에 의해 처리)
  • DOM 이벤트 콜백

에 이 경우 다음과 같이하십시오.

// inject $rootScope and do $apply on it 
angular.service('Channel', function($rootScope) { 
    // ... 
    return { 
    init: function(channelId, clientId) { 
     // ... 
     socket.onmessage = function(msg) { 
     $rootScope.$apply(function() { 
      that.publish(args[0], args[1]); 
     }); 
     }; 
    } 
    }; 
}); 
+1

이것은 도움이되었습니다. DOM/jQuery 이벤트의 경우이 작업을 수행하려면 나에게 의미가 있었고이를 수락 할 수있었습니다. – duma

+0

차가움. 근본 범위를 주입 할 수 있는지 몰랐습니다. – heneryville

+4

'setTimeout' 콜백의 경우, 대신'$ timeout' 서비스를 사용하십시오 : https://coderwall.com/p/udpmtq – itghisi