当我收到ws消息时,我在设置结果时遇到问题。
我有一个控制器,当我单击某个按钮时,它会调用getStops
函数。
在这个函数(getStops
(中,我使用 ws 连接,当我收到消息
(在ws.onmessage
(时,我需要获取tramState['stop_id']
并将其连接到$scope.current_stop
。
然后在ul
列表中,适当的li
应该变为活动状态。
但它不会发生,$scope.current_stop
总是null
.
问题出在哪里?谢谢。
angular.module('tramApp').
controller('tramController', ['$scope', 'tramAPIService', function($scope, tramAPIService) {
$scope.trams = [];
$scope.stops = [];
$scope.active_tram = null;
$scope.current_stop = null;
$scope.getStops = function (tram_id) {
tramAPIService.getStops(tram_id)
.then(stops => $scope.stops = stops);
$scope.active_tram = tram_id;
const ws = new WebSocket(`ws://192.168.0.103:8080/tram_ws/?tram_id=${tram_id}`);
ws.onmessage = (message) => {
let tramState = JSON.parse(JSON.parse(message.data));
$scope.current_stop = (tramState['stop_id'] !== "None") ? Number(tramState['stop_id']) : null;
console.log(tramState);
};
};
tramAPIService.getTrams()
.then(trams => $scope.trams = trams);
}]);
<ul class="list-group">
<li
class="list-group-item"
ng-repeat="s in stops"
ng-class="{'active': s.stop_id === current_stop}">
{{ s.stop_id }}, {{ s.stop_name }}
</li>
</ul>
问题是,您正在从 AngularJS 上下文外部更新角度$scope
变量,其中 angularjs 不知道这些更改,因此更改不会反映在 UI 中。更新绑定的过程称为摘要循环系统$scope
。在这种情况下,您必须手动触发此过程才能在屏幕上查看更新。
您可以通过两种方式触发此过程
- 通过在
$scope
上调用$apply
方法 -
或者
$timeout
和$applyAsync
方法。(首选方式(ws.onmessage = (message) => { let tramState = JSON.parse(JSON.parse(message.data)); $scope.$applyAsync(function(){ $scope.current_stop = (tramState['stop_id'] !== "None") ? Number(tramState['stop_id']) : null; }); };