我对下面的代码有问题。我有 prices
工厂,它返回包含通过 websocket 从服务器接收的价格的对象。单击创建
按钮后发送价格。问题是 main.prices
变量根本没有更新。我可以通过 Check
按钮检查所有内容,这证实了这一点。 Prices.data
已更新,但 this.prices
未更新,但它引用了同一个对象,所以我认为它也应该更新。您知道为什么下面的内容不能按预期工作吗?
angular.module('myApp', ['ngWebSocket'])
.factory('ws', ['$websocket', function($websocket){
var url = 'ws://localhost/websocket';
var ws = $websocket(url);
return ws;
}])
.factory('prices', ['ws', function(ws){
var prices = {
data: [],
clear: function(){
this.data = [];
},
create: function(){
ws.send('send')
}
}
ws.onMessage(function(message){
message = JSON.parse(message.data);
var type = message.type;
if (type == 'new prices'){
prices.data = message.data;
}
});
return prices;
}])
.controller('main', ['prices', function(prices){
this.prices = prices.data;
this.check = function(){
console.log('works ', prices.data);
console.log('not works ', this.prices);
};
this.create = function(){
prices.create();
};
this.stop = function(){
prices.clear();
};
}]);
<div ng-controller="main as main">
{{ main.prices }}
<button ng-click="main.create()">Create</button>
<button ng-click="main.stop()">Stop</button>
<button ng-click="main.check()">Check</button>
</div>
最佳答案
您发布的代码存在很多问题(正在处理 fiddle ,因此我可以帮助修改它)...
第一个变化:
if (type == 'new prices'){
prices.data = message.data;
}
致:
if (type == 'new prices'){
prices.data.length = 0;
prices.data.push.apply(prices.data,message.data) ;//copy all items to the array.
}
<小时/>
从可读性/可维护性的 Angular 来看,您应该只使用 this.prices
与 this.prices.data
。当您只能使用价格时,将它们映射到其他变量会很困惑。另请注意,我将其更新为不断使用“that”以避免任何类型的上下文 this
问题。
.controller('main', ['prices', function(prices){
var that = this;
that.prices = prices;
that.check = check;
that.create = create;
that.stop = stop;
function check(){
console.log('works ', that.prices.data);
console.log('not works ', that.prices);
}
function create(){
that.prices.create();
}
function stop(){
that.prices.clear();
}
}]);
关于javascript - AngularJS Controller 的变量未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30870374/