2013-11-26 25 views
0

這裏是我的情況: 我的應用程序中有一個「編輯」屏幕。要加載這個屏幕,我通過一個window.postMessage事件傳遞一個對象。我在我的控制器中爲編輯頁面監聽postMessage事件,並將傳入的對象分配給我的作用域中名爲「患者」的屬性。然後,在編輯頁面標記中,我正在使用ng-repeat綁定到「患者」對象上的數組。問題是,頁面不會更新以顯示接收到的數據。
這裏是我的事件處理程序的代碼看起來像在我的控制器:angularjs綁定不會顯示,除非我進行GET調用

window.addEventListener("message", function(event) { 
    if (event.data.view === 'edit') { 
     $scope.patient = event.data.patient; 
    } 
}); 

這裏的標記是什麼樣子綁定到病人對象:

<div ng-repeat="dataItem in patient.fields | filter:{display:true}"> 
    <div class="row" > 
     <div class="col-xs-12"> 
      {{dataItem.displayName}}: 
     </div> 
    </div> 
    <div class="row" > 
     <div class="col-xs-12"> 
      <input type="text" style="width: 100%;" ng-model="dataItem.value" /><br /> 
     </div> 
    </div> 
</div> 

數據加載正確和$ scope.patient屬性獲得完全填充,但屏幕不會更新。但是,如果我使用RESTAngular添加簡單的'GET'調用,並且甚至不使用調用的結果,那麼頁面會正確更新。爲什麼是這樣,我能做些什麼來讓頁面在沒有無意義的RESTAngular調用的情況下更新?下面是與RESTAngular調用工作代碼:

window.addEventListener("message", function(event) { 
    if (event.data.view === 'edit') { 
     patient = PatientRestangular.one('patients', event.data.patientId); 
     //this is a hack 
     //the data will not load on the edit screen without a call to 'get()' 
     patient.get().then(function(){ 
      $scope.patient = event.data.patient; 
     }); 
    } 
}); 
+0

你的事件監聽器之外的角「範圍」,則需要使用'$ apply'爲了以確定數據發生了變化。您應該嘗試使用'$ scope。$ on'或'$ scope。$ watch'來設置事件偵聽器。 –

回答

4

嘗試$apply

$scope.$apply(function(){ 
    $scope.patient = event.data.patient; 
}); 
+0

非常感謝!這工作!你如何知道$ apply?我只是搜索文件,我沒有看到它... –

+0

@TylerJones你可以在這裏閱讀http://docs.angularjs.org/api/ng.$ro​​otScope.Scope – AlwaysALearner

相關問題