Angularjs model changes after websocket data is deleted from the server

I am trying to change my angular model after clicking on the website from the server. How can I change values ​​like $scope.contacts every time the server serves new data ..?

I'm not sure if this is possible using $apply . I know that I can access the DOM element to get 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 the outside without creating angular modules, since I use relative data sources that emit change events. Is there a simple way to do this, as 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 } 
+7
source share
3 answers

Take a look at the 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 its controller:

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

just do it as below

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

Well, the notable answer, of course, is not the β€œeasy way” at the request of the OP. Here is a much simpler solution.

Get the area, wherever you want, in your own JavaScript code:

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

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

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

Here's the JSFiddle .

+1
source

All Articles