AngularJS控制器的变量未更新

时间:2015-06-16 14:20:59

标签: javascript angularjs websocket

我遇到以下代码问题。我有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>

2 个答案:

答案 0 :(得分:2)

您发布的代码存在很多问题(在小提琴上工作,所以我可以帮忙重做)......

首先改变:

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 vs this.prices.data。当你只能使用价格时,将它们映射到其他变量会让人感到困惑。另请注意,我更新了它以使用&#34;那&#34;不断避免任何类型的上下文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();
    }
}]);

答案 1 :(得分:1)

要添加到上一个响应中,clear()上也存在问题:

var prices = {
    ...
    clear: function(){
        this.data = [];
    },
    ...
}

当您使用this.data = []进行清除时,实际上是在创建一个新的空数组,并将其存储在this.data prop中,因为这是一个新数组,主控制器上的引用 - &gt; this.prices = prices.data;仍然指着旧的。如果你需要删除数组中的元素,只需使用this.data.length = 0,因为Nix指出了另一种方法。这将使所有引用保持同步,因为您正在使用原始数组