The AngularJS Controller variable is not updated

综合技术 2018-06-17

I have problem with below code. I have prices
factory which returns object containing prices received from server by websocket. Prices are sent after button Create
is clicked. Problem is that main.prices
variable is not updated at all. I can check everything by Check
button, which confirms this.
is updated, but this.prices
is not, but it refers the same object, so I thought it should be updated as well. Do you have any ideas why below does not work as expected?

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(){
       = [];
            create: function(){

            message = JSON.parse(;
            var type = message.type;

            if (type == 'new prices'){

        return prices;

    .controller('main', ['prices', function(prices){
        this.prices =;

        this.check = function(){
            console.log('works ',;
            console.log('not works ', this.prices);

        this.create = function(){

        this.stop = function(){

{{ main.prices }}

There are a lot of issues with the code you posted (working on a fiddle so i can help rework it) ...

First change :

if (type == 'new prices'){ =;


if (type == 'new prices'){ = 0;, ;//copy all items to the array.

From a readability / maintainability point of view you should just use this.prices
. It's confusing to map them to other variables, when you can just use prices. Also note that I updated it to use "that" constantly to avoid any type of context 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 ',;
        console.log('not works ', that.prices);

    function create(){
    function stop(){
Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!


@JesseS_BrieBug will be in Houston tonight, presen... Jesse Sanders is the founder and CEO of BrieBug, a premier broker of techno...
How do I disable an HTML element with Angular ? Set the disabled attribute to the result of an expression and Angular will ...
Build a real time app with MEAN2, angular-cli and ... Build a real time app with MEAN2, angular-cli and A smal...
AngularJS and Angular 2+: a Detailed Comparison This article compares the major differences between the the original AngularJS a...
Angular timer with 2 counters Creating an angular application with grunt, the applicat...