我有一个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.