I'm not quite sure the title is the best description but I was wondering what the best method would be if I had some event that occurs outside of the Angular digest loop, to trigger a digest loop? In an application I'm working on, I'm using Socket.io to pass data back and forth from other applications within the network. There are some events from Socket.io that may be used to update models within the current Controllers $scope. These changes aren't reflected in the UI until a digest loop occurs though. It's prefered that I not have to call $scope.$apply() to prevent running into issues with Angular already being in a loop.
I know I could use $timeout() and just drop my function within there and set the timeout to be 0 seconds. That's what I'm currently using and it works fine but I'm wondering if this is the best approach?
Example JS
var app = angular.module('MyApp',[]);
var socket = io.connect('http://localhost:3000');
app.controller('MyAppController',['$scope',function($scope) {
$scope.connections = 0;
socket.on('connect',function(sock) {
sock.on('event',function() {
$scope.connections++;
};
};
}]);
Example HTML
<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
<head></head>
<body ng-controller="MyAppController">
<p>Connections: {{connections}}</p>
<script src="angular.min.js"></script>
</body>
</html>
Obviously this is a very stripped down, as basic as possible example. It's not the ACTUAL code in use, but represents the same issue. When the event is raised from socket.io, the $scope.connections variable is incremented but the UI doesn't reflect the change until something else triggers a digest loop, $scope.$apply() is called, or I use $timeout().
Once again, I have code that works, just wondering what the best approach to this is.
Thanks