AngularJS没有用Websocket更新datanbinding

AngularJS is not updating datanbinding with Websocket

本文关键字:更新 datanbinding Websocket 有用 AngularJS      更新时间:2023-09-26

你好,我正在尝试与AngularJS结合websocket进行数据绑定。当Websocket触发响应时,数据应该显示在站点上,但它并不像我想象的那样工作。

这是我的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();
  });
这是我的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>

首先Field1和Field2为空。但是当Websocket接收数据时,接收到的resp数据是正确的,工作数据也被正确填充。但网站上没有任何变化。也许你可以帮我改正我的代码。

编辑我用$scope.$apply()调用补充了我的javascriptcoding,但它没有效果:

   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();
  });

该变量仅在创建控制器时在$scope.workdata = that.workdata;行中填充。修改that.workdata后,不会更新$scope.workdata,因此手表{{workdata.field1}}仍显示原始值。

要解决这个问题,修改作用域的值,并确保当你在AngularJS的结构之外修改作用域时调用$scope.$apply。WebSocket回调不是由AngularJS处理的,所以你必须调用$scope.$apply来通知AngularJS重新触发它的循环。

另外,我强烈建议在AngularJS结构中编写应用程序,而不是像你现在这样使用AngularJS作为库。