Search code examples
javascriptangularjsrestangular

angularjs bindings won't show unless i make a GET call


here is my situation: I have an "edit" screen in my app. To load this screen, i am passing in an object through a window.postMessage event. I am listening for this postMessage event in my controller for the edit page and assigning the passed-in object to a property on my scope called "patient". Then, in the edit page markup, i am using ng-repeat to bind to an array on my "patient" object. The problem is, the page does not update to show the received data.
Here is what my event handler code looks like in my controller:

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

Here is what the markup looks like to bind to the patient object:

<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>

The data loads correctly and the $scope.patient property is getting fully populated, but the screen does not update. However, if I add a simple 'GET' call using RESTAngular, and don't even use the result of the call, the page updates correctly. Why is that and what can I do to get the page to update without the meaningless RESTAngular call? Here is the code that works with the RESTAngular call:

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;
        });
    }
});

Solution

  • Try $apply:

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