插座IO消息不't更新Angular变量
Socket.IO message doesn't update Angular variable
我有一个socket.io客户端服务器设置,AngularJS在客户端上运行。
// 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);
});
});
正如所观察到的,它本质上发射具有存储在变量msg
中的数据的message
事件。
然后我得到了以下客户端代码。
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;
});
});
我现在面临一个奇怪的问题。当我编写下面的代码片段来打印frontEnd
时,它不会显示出来。但是console.log(msg);
是有效的,它向我展示了从变量msg
发出的数据。
<body ng-app="AdminApp">
<div ng-controller="StatsController">
<p>{{frontEnd}}</p> //Doesn't show anything
</div>
</body>
有人能帮我吗?
您需要用$scope.$apply(function() {})
包装模型的更改(更改$scope
上的属性),以便更新视图。
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()用于从外部执行angular中的表达式棱角分明的框架。(例如,从浏览器DOM事件,setTimeout、XHR或第三方库)。因为我们正在呼叫我们需要执行适当的范围生命周期的角度框架异常处理,执行监视。
来自官方的Angular文档
这可能是因为socket.on('message', function (msg) {..
缺乏角度知识。它发生在角外。
然后,如果你有超出角度的东西,那么你必须告诉角度更新,因为有东西要更新
在$scope.frontEnd = msg;
之后使用$scope.$apply()
或者更优选将其包裹在$timeout
中,作为
$timeout(function() {
$scope.frontEnd = msg;
});
这里很好地解释了为什么CCD_ 12更优选。
相关文章:
- 在日期更改后更新Angular UI引导程序日期选择器选项
- 如何使用不同视图的JSON对象更新angular js中的全局JSON字段
- 从$http.get调用更新Angular作用域变量
- 更新angular ng模型中的HTML输入值更改
- 从返回的 MongoDB 对象更新 Angular.js $scoped
- 更新 Angular $interval 中的变量会导致其他函数运行
- 多视图未更新Angular JS中的变量
- 点击按钮加载新的json url并更新Angular中的View
- 正在更新Angular中的多个$scope属性
- 可以't更新angular.js中的变量
- 服务变量未更新Angular JS中的指令
- 更新Angular Directive的值时出现问题's模型,同时从表单的监视进行更新
- 成功后使用dropzone更新angular js上的选项卡
- 如何更新Angular UI网格中的数据
- 美元的范围.currentPage没有更新——Angular Ui分页
- 从chrome dev. tools更新angular .js工厂
- 从javascript中更新angular表单
- 更新angular-flexslider的Json数据'removeSlide'
- 更新angular中的作用域值
- Angularjs没有更新angular模板给出的标签