Angularjs data is not updated on call of $apply

119 Views Asked by At

I have a controller that reads data via rest and displays it in a table - this part is working fine. Additionally i added a WebSocket and want to update the table if Websocket receives data. Here is the Code:

app.controller('allBookingsCtrl', function($scope, $http, currentUser){
    $scope.bookingsList = [];
    var ws = new WebSocket(wsRootUrl + '/allbookings');
    ws.onmessage = function(message){
        $scope.$apply(function(){
            $scope.bookingsList = message.data;
            alert(message.data);//displays correct data!
        });
    };
    $http.get(rootUrl + '/timetracker/booking/all').success(function(response) {
        $scope.bookingsList = response;
    });
});

The problem is the table is not updated on call of apply. I debugged and could trigger onmessage by changing data from another browser. the content of data is also correct, no error is thrown.

So how to update the table/scope with data received by websocket?

here is html:

<table ng-controller="allBookingsCtrl" class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>user</th>
                <th>project</th>
                <th>start</th>
                <th>end</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="booking in bookingsList">
                <td>{{$index + 1}}</td>
                <td>{{booking.usersProjects.user.name}}</td>
                <td>{{booking.usersProjects.project.name}}</td>
                <td>{{booking.start | date:'yyyy-MM-dd HH:mm:ss' }}</td>
                <td>{{booking.end | date:'yyyy-MM-dd HH:mm:ss' }}</td>
            </tr>
        </tbody>
    </table>

Small Edit: if i add alert(data); at the end of on message i see the alert with correct data! So only the apply with the list isn't working correctly.

added plunkr I tried to reproduce this in plunkr and with no websocket - tried to get the update on ng-click. But this isn't working neither - here the click is not doing anything.

1

There are 1 best solutions below

3
On

Can you change this line

$scope.bookingsList = data;

to

$scope.bookingsList = message.data;