title: AngularJS - Best method to trigger digest from outside of Angular
body: <p>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. </p>
  
  <p>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?</p>
  
  <p>Example JS</p>
  
  <pre><code>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++;
          };
      };
  }]);
  </code></pre>
  
  <p>Example HTML</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en" ng-app="MyApp"&gt;
  &lt;head&gt;&lt;/head&gt;
  &lt;body ng-controller="MyAppController"&gt;
      &lt;p&gt;Connections: {{connections}}&lt;/p&gt;
      &lt;script src="angular.min.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>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().</p>
  
  <p>Once again, I have code that works, just wondering what the best approach to this is.</p>
  
  <p>Thanks</p>