Hello I'm trying out databinding with AngularJS in combination with an websocket. When the Websocket fires a response, the data should be displayed on a site, but it doesn't work the way I thought.
This is my JS:
function WebApp() {
this.webSocket = null;
this.workdata = null;
var that = this;
this.AngularApp = angular.module('AngularApp', []);
this.AngularApp.controller('AngularCtrl', function ($scope) {
$scope.workdata = that.workdata;
});
this.initializeWebsocket = function() {
this.webSocket = new WebSocket('ws://url2ws');
this.webSocket.onmessage = function(resp) {
that.workdata = JSON.parse( resp.data );
$('#wait').hide();
}
}
var app = null;
$( 'document' ).ready(function() {
$('#wait').show();
app = new WebApp();
app.initializeWebsocket();
});
And this is my HTML:
<!doctype html>
<html class="no-js" ng-app="AngularApp">
<head>
<script src="js/vendor/jquery.js"></script>
<script src="js/app.js"></script>
<script src="js/angular.min.js"></script>
</head>
<body ng-controller="AngularCtrl">
Field1 : {{workdata.field1}}<br />
Field2 : {{workdata.field2}}
</body>
</html>
At first Field1 and Field2 is empty. But when the Websocket is receiving data, the received data in resp is correct and workdata is also filled correctly. But nothing changes on website. Maybe you can help me to correct my code.
EDIT I have complemented my javascriptcoding with the call of $scope.$apply() but it has no effect:
function WebApp() {
this.webSocket = null;
this.workdata = null;
this.$scope = null;
var that = this;
this.AngularApp = angular.module('AngularApp', []);
this.AngularApp.controller('AngularCtrl', function ($scope) {
$scope.workdata = that.workdata;
that.$scope= $scope;
});
this.initializeWebsocket = function() {
this.webSocket = new WebSocket('ws://url2ws');
this.webSocket.onmessage = function(resp) {
that.workdata = JSON.parse( resp.data );
that.$scope.$apply();
}
}
var app = null;
$( 'document' ).ready(function() {
$('#wait').show();
app = new WebApp();
app.initializeWebsocket();
});