我正在尝试为通过WebSockets接收的信息创建客户端(不重要)。该信息位于JSON容器中。 我用
Buildings = JSON.parse(a_Data.data);
将字符串解析为JSON并将该Javascript对象保存到驻留在我工厂中的名为Buildings的变量中。之后,该变量在我的控制器内正确暴露给$ scope。 但是,我的视图根本没有更新(更新未被触发),而正在正确设置建筑物。 我在某处读到这是因为AngularJS只是处理由它自己创建的变量,这就是为什么建议将数组添加到由Angular创建的数组中(并且正手将其长度设置为0以清除它)。但是在这种情况下,我有一个对象,这就是推送技巧不起作用的原因。 使用
angular.fromJson
不会改变任何东西。 我还读到你可以使用
或多或少强制更新$scope.$apply
然而,如果可能的话,需要将$ scope传递给工厂,我希望尽可能避免。
(将对象添加到数组是一种有效的解决方法,但只要有解决方法,它就不是我想要的了。)
HTML
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script>
<script src="https://rawgit.com/gdi2290/angular-websocket/v1.0.9/angular-websocket.js"></script>
<script src="js/protocol.js"></script>
<body>
<div ng-app="MiniGame">
<section ng-controller="SomeController">
<ul>
<li ng-repeat="data in buildings">
{{ data.type }}
</li>
</ul>
</section>
</div>
</body>
</html>
protocol.js
angular.module('MiniGame', ['ngWebSocket'])
.factory('GameProtocol', function($websocket, $q) {
var socket = $websocket('ws://localhost:9002');
var m_Buildings = { };
console.log("Example ", m_Buildings);
function Setup(){
socket.onMessage(OnMessage);
console.log("Startup complete");
}
function OnMessage( a_Data ){
m_Buildings = angular.fromJson(a_Data.data);
console.log(m_Buildings);
}
function RequestBuildings(){
dataStream.send(JSON.stringify({ action: 'GetBuildings' }));
}
return {
Setup : Setup,
buildings : m_Buildings
};
})
.controller('SomeController', function ($scope, GameProtocol) {
$scope.GameProtocol = GameProtocol;
$scope.GameProtocol.Setup();
$scope.buildings = GameProtocol.buildings;
});
答案 0 :(得分:0)
使用
angular.copy(angular.fromJson(a_Data.data), m_Buildings);
而不是
m_Buildings = angular.fromJson(a_Data.data);
解决了这个问题。
有关详细信息,请查看此答案。 Angular: update in factory model does not reflect in controller