Socket.IO信息不更新角度变量 [英] Socket.IO message doesn't update Angular variable
问题描述
我有一个客户端上运行AngularJS一个socket.io客户端 - 服务器设置。
// Server.js
VAR IO =要求('socket.io')(服务器);
io.on('连接',函数(插座){
socket.on('消息',函数(MSG){
//console.log(msg);
的console.log(味精);
io.emit('消息',味精);
});
});
根据我们的观察,它本质上发出的消息
事件与存储在变量中的数据信息
。
然后,我有以下的客户端code。
VAR容器= angular.module(AdminApp,[]);container.controller(StatsController功能($范围){ 变种插座= io.connect(); socket.on('消息',函数(MSG){
的console.log(味精);
$ scope.frontEnd =味精;
});
});
我现在面临一个奇怪的问题。当我写了下面的code段打印前端
,它不会显示出来。但的console.log(味精);
的作品,它显示了我从变量所发出的数据信息
<机身NG-应用=AdminApp> < DIV NG控制器=StatsController>
&所述p为H.; {{前端}}&下; / P> //不显示任何东西
< / DIV>< /身体GT;
谁能帮我?
您需要换行模式的改变(改变对 $作用域属性
),其中 $范围。$应用(函数(){})
,以更新视图。
VAR容器= angular.module(AdminApp,[]); container.controller(StatsController功能($范围){ 变种插座= io.connect(); socket.on('消息',函数(MSG){
的console.log(味精);
。$ $范围应用(函数(){$ scope.frontEnd =味精;});
});
});
$申请()用于从外侧角来执行一个前pression
角框架。 (例如,从浏览器的DOM事件,
setTimeout的,XHR或第三方库)。因为我们是调用到
角框架,我们需要执行的适当范围的生命周期
异常处理,执行手表。
块引用>从官方角文档
I have a socket.io client-server setup with AngularJS running on the client.
// Server.js var io = require('socket.io')(server); io.on('connection', function (socket) { socket.on('message', function (msg) { //console.log(msg); console.log(msg); io.emit('message', msg); }); });
As observed, it essentially emits a
message
events with the data stored in the variablemsg
.And then I have the following client code.
var container = angular.module("AdminApp", []); container.controller("StatsController", function($scope) { var socket = io.connect(); socket.on('message', function (msg) { console.log(msg); $scope.frontEnd = msg; }); });
I now am facing a weird problem. When I write the following code snippet to print
frontEnd
, it doesn't show up. But theconsole.log(msg);
works and it shows me the data emitted from the variablemsg
.<body ng-app="AdminApp"> <div ng-controller="StatsController"> <p>{{frontEnd}}</p> //Doesn't show anything </div> </body>
Can anyone help me out?
解决方案You need to wrap the change of the model (changing properties on the
$scope
), with$scope.$apply(function() {})
in order to to update the view.var container = angular.module("AdminApp", []); container.controller("StatsController", function($scope) { var socket = io.connect(); socket.on('message', function (msg) { console.log(msg); $scope.$apply(function() { $scope.frontEnd = msg; }); }); });
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.
From the official Angular Documentation
这篇关于Socket.IO信息不更新角度变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!