Richard Searle's Blog

Thoughts about software

Angular.js and Server Sent Events wiring

Posted by eggsearle on April 8, 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 {{data}}
</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>
Advertisements

One Response to “Angular.js and Server Sent Events wiring”

  1. […] Angular.js and Server Sent Events wiring […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: