我有以下代碼的問題。我有prices
工廠,它返回包含由websocket從服務器收到的價格的對象。在點擊按鈕Create
之後發送價格。問題是main.prices
變量根本沒有更新。我可以通過Check
按鈕檢查一切,這證實了這一點。 Prices.data
已更新,但this.prices
不是,但它指的是同一個對象,所以我認爲它也應該更新。你有什麼想法,爲什麼下面不能按預期工作?AngularJS控制器的變量未更新
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>
您處理引用問題。 – Nix