[英]AngularJS controller's variable is not updated
我對以下代碼有疑問。 我有prices
工廠,它返回包含通過websocket從服務器收到的價格的對象。 單擊Create
按鈕后發送價格。 問題是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>
您發布的代碼有很多問題(在小提琴上工作,所以我可以幫助重做)...
第一次更改:
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.
}
從可讀性/可維護性的角度來看,您應該只使用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();
}
}]);
要添加到上一個響應中,您在clear()上還存在一個問題:
var prices = {
...
clear: function(){
this.data = [];
},
...
}
當您使用this.data = []進行清除時,您實際上是在創建一個新的空數組,並將其存儲在this.data屬性中,並且由於這是一個NEW數組,因此主控制器上的引用-> this.prices = price 。數據; 仍然指向舊的。 如果您需要刪除數組中的元素,只需使用this.data.length = 0即可,如Nix指出的另一種方法。 由於您正在重新使用原始數組,因此將使所有引用保持同步
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.