AngularJS没有用Websocket更新datanbinding
AngularJS is not updating datanbinding with Websocket
你好,我正在尝试与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作为库。
相关文章:
- Javascript循环不会自我更新
- 添加文字和评论功能更新Div
- AngularJS:ng之后,重复$scope值未按预期更新
- 如何通过数组更新角度子范围
- Ajax聊天消息重复而不仅仅是更新
- 通过CSV文件上载更新数据库表
- 平均值:无法将数据更新到数据库
- $rootScope未使用forEach进行更新
- d3基于用户选择动态更新节点
- 有条件更新d3.js力图中节点的最佳方法
- Angular:更新一次性绑定的数据
- Javascript更新孙窗口中的表单元素
- 使用AngularJS中的筛选器更新给定的表
- 从选项页面更新chrome扩展清单权限
- 如何在不刷新页面的情况下更新显示框
- 延期承诺值未更新/解析/延期
- 标记的实时更新,无需加载页面谷歌地图API V3
- 使用mongodb更新中的一个变量
- 访问jsrender模板中的全局javascript变量并更新它
- AngularJS没有用Websocket更新datanbinding