javascript – Socket.IO消息不更新Angular变量

前端之家收集整理的这篇文章主要介绍了javascript – Socket.IO消息不更新Angular变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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中.

然后我有以下客户端代码.

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() 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.

来自官方Angular Documentation

原文链接:https://www.f2er.com/js/149950.html

猜你在找的JavaScript相关文章