Friday, November 29, 2013

Yet Another Integration: AngularJS

I had some spare time, so I decided to put together some code to make a PoC integration between our Lightstreamer JavaScript client library and Google's AngularJS.

The integration went smoothly: simply prepare the view using AngularJS syntax, then populate the associated model object with the data flowing in from the Lightstreamer subscription. At each update, ask AngularJS to refresh the view and you're done!

Let me show it to you right here through a simple recipe.

You need a bit of HTML:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.9/require.min.js"></script>
<script src="https://www.lightstreamer.com/demo/commons/lightstreamer.js"></script>
<div ng-app ng-cloak>
<div ng-controller="Controller">
<div ng-repeat="item in items">
{{item.stock_name}}: {{item.last_price}}
</div>
</div>
</div>
And a pinch of JavaScript:
function Controller($scope) {
$scope.items = {};
require(["LightstreamerClient","Subscription"],function(LightstreamerClient,Subscription) {
var lsClient = new LightstreamerClient("https://push.lightstreamer.com/","DEMO");
lsClient.connect();
var subscription = new Subscription("MERGE",["item2","item17"],["stock_name","last_price"]);
subscription.setDataAdapter("QUOTE_ADAPTER");
lsClient.subscribe(subscription);
subscription.addListener({
onItemUpdate: function(info) {
var itemName = info.getItemName();
if (!$scope.items[itemName]) {
$scope.items[itemName] = {};
}
info.forEachChangedField(function(fieldName,fieldPos,val) {
$scope.items[itemName][fieldName] = val;
});
$scope.$apply();
}
});
});
}
view raw LS_AngularJS.js hosted with ❤ by GitHub
And you get this:

After completing my exercise, I discovered ng-grid. I wanted to try that too and so I quickly did.

You can head to GitHub to find the full source of the complete demo application.

And you can see the final result live.