AngularJS with SignalR AngularJS with SignalR angularjs angularjs

AngularJS with SignalR


$scope does not exist in this context as that's something injected when a controller is created and a new child scope is made. However, $rootScope is available at the time you need.

Also, be aware $emit() goes upward and your controller scopes wont see it. You would either need to switch to $broadcast() so the event goes downwards or inject $rootScope as well to the controllers you want to be able to subscribe to 'numberOfIncidents'

Check out the angular docs and a useful wiki on scopes.


Here is a great example showing how to wrap the proxy in a service and use $rootScope for event pub/sub.

http://sravi-kiran.blogspot.com/2013/09/ABetterWayOfUsingAspNetSignalRWithAngularJs.html


As already noted in johlrich's answer, $scope is not avaliable inside proxy.on. However, just switching to $rootScope will most likely not work. The reason for this is because the event handlers regisrered with proxy.on are called by code outside the angular framework, and thus angular will not detect changes to variables. The same applies to $rootScope.$on event handlers that are triggered by events broadcasted from the SignalR event handlers. See https://docs.angularjs.org/error/$rootScope/inprog for some more details.

Thus you want to call $rootScope.$apply() from the SignalR event handler, either explicitly

proxy.on('numberOfIncidents', function (numOfIncident) {  console.log(numOfIncident);  $scope.$apply(function () {    $rootScope.$emit('numberOfIncidents', numOfIncident);  });});

or possibly implicitly through $timeout

proxy.on('numberOfIncidents', function (numOfIncident) {  console.log(numOfIncident);  $timeout(function () {    $rootScope.$emit('numberOfIncidents', numOfIncident);  }, 0);});