Search code examples
angularjscakephpwebsocketngresourceratchet

How can I update the $scope in AngularJS when a server sided update occurs?


Background

  1. I am trying to make a single page real-time application that uses a PHP , MYSQL back end and AngularJS frontend

  2. My back end is using CakePHP framework which serves a JSON API and the front uses ngResource in AngularJS to access this API.

  3. I have got 'Ratchet WebSockets for PHP' working, which can trigger a response to the browser via websockets when something updates in the back end.


My Incomplete Solutions

Solution 1: Use the response via the websocket to update the AngularJS $scope object through some kind of $scope.model.push(websocket.data) method?

Solution 2: Use the response via the websocket to trigger Refresh on the ngResource which would refresh the $scope object completely?


Question

Are my solutions viable? and how could I achieve it ?


Solution

  • You just need to read events from the WS and populate them using $emit and $broadcast, then your controllers can subscribe to whichever events are relevant to them.

    Take a look at:

    angular websocket factory

    AngularJS and WebSockets beyond