Angularjs model changes after websocket data push from server Angularjs model changes after websocket data push from server angularjs angularjs

Angularjs model changes after websocket data push from server


Look at socket.io angular service:

angular.module('app')  .factory('socket', ['$rootScope', function ($rootScope) {    var socket = io.connect();    return {      on: function (eventName, callback) {        socket.on(eventName, function () {            var args = arguments;          $rootScope.$apply(function () {            callback.apply(socket, args);          });        });      },      emit: function (eventName, data, callback) {        socket.emit(eventName, data, function () {          var args = arguments;          $rootScope.$apply(function () {            if (callback) {              callback.apply(socket, args);            }          });        })      }    };  }]);

and controller using it:

angular.module('app')  .controller('Controller', ['$scope', 'socket', function ($scope, socket) {    socket.emit('register')    socket.on('register', function (data) {        $scope.data = data;    });}]);


just do it like below

 socket.onmessage = function (event) {     scope.$apply(function(){       // modify scope values here      }    };


Well, the marked answer is certainly not a "simple way" as requested by OP. Here's a much simpler solution.

Retrieve the scope wherever you want in your own JavaScript code:

var scope = angular.element($("#elementID")).scope();

Change a value in your Angular $scope variable, but from your external JavaScript:

scope.$apply(function() {    scope.yourArrayForExample.push({name: 'New, external value'});});

Here's a JSFiddle.