Richard Searle

home

Angular.js and Server Sent Events wiring

08 Apr 2012

SSE provides a standardized HTML5 way to push data over an HTTP connection. angular is an interesting Javascript MVC framework that uses binding to provide a very clean implementation. The general Angular documentation covers interactions that are initiated from the browser. Implementing an external push into Angular was not clearly described until the 1.0 release. The following example uses a snapshot from upcoming angular 1.0 release. Strings received via /events, tagged with right, are displayed
</pre>
<!DOCTYPE html>
<html>
<head>
 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 <title>AngularJS and SSE</title>
 <script type='text/javascript' src="http://ci.angularjs.org/job/angular.js-angular-master/ws/build/angular.js"></script>
</head>
<body ng-app>
 <div ng:controller="Main">
Value 
</div>

<script type='text/javascript'>//<![CDATA[


var source = new EventSource('/events');

function Main($scope, $window) {
 source.addEventListener('right', function(e) {
 $scope.$apply(function() {
 $scope.data = e.data;
 });
 },false);
}
//]]>

</script>
</body>
</html>
<pre>