Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs model changes after websocket data push from server

I'm trying to change my angular model after a websocket push from the server. How is it possible to change values like $scope.contacts each time the server serves new data..?

I'm not sure if it is possible by using $apply. I know that I can access the DOM element retrieve the scope and then change the values, but there should be a better solution!

I'm really interested in a solution to update the angular model from outside without creating angular modules since I'm using relative data sources that emit change events. Is there no simple way to do that like in Backbone.js where you can say:

var book = new Backbone.Model({ title: 'value' });
book.set("title", "A Scandal in Bohemia");

What I want in angularjs is something like:

function MyController($scope) {
    $scope.contacts = [];
}

datasource changed -> function () {
    MyController.set('contacts', 'value'); // change angular scope property
}
like image 428
Pascal Bayer Avatar asked Feb 05 '13 08:02

Pascal Bayer


2 Answers

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

}]);
like image 170
Maxim Grach Avatar answered Sep 21 '22 17:09

Maxim Grach


just do it like below

 socket.onmessage = function (event) {
     scope.$apply(function(){
       // modify scope values here 
     }
    };
like image 34
Ajay Beniwal Avatar answered Sep 18 '22 17:09

Ajay Beniwal