P_M
P_M

Reputation: 2942

Cannot bind data from AngularJS factory

I am new with AngularJS, and take webSocket example as base for my application https://github.com/AngularClass/angular-websocket/tree/master/example Application should take jSon data from webSocket and populate UI. Example contains factory with colection variable, and binding gives result on HTML template, but when I add searchStatus variable I cannot see its auto update (Binding) on UI. Why?

    <div ng-app="portScanner">
        <h2>Port scanner</h2>

        <div ng-controller="SimplePortScannerController">

            Status : {{ searchStatus }}

            <form ng-submit="submit(address)">
                <input type="text" ng-model="address" autofocus required>
                <button type="submit">Check ports</button>
            </form>

        {{sum}}<br>

        <div ng-repeat="message in Messages.collection | orderBy:'-timeStamp' track by $index">
            <!--{{message.statusString}}-->
            {{message}}
            <br>
        </div>

        </div>
    </div>

Java script code

var angularApp = angular.module("portScanner", ['ngWebSocket']);

angularApp.controller('SimplePortScannerController', function ($scope, Messages) {
    $scope.sum = 0;
    if ($scope.address==null){
        $scope.address = "192.168.0.1";
    }
    $scope.Messages = Messages;
    $scope.submit = function (address_message) {
        if (!address_message) {
            return;
        };
        Messages.send({
            address : address_message
        });
        $scope.sum = $scope.sum + 1;
    };
});

angularApp.factory('Messages', function ($websocket) {
    var ws = $websocket('ws://localhost:8080/portscanner2/scanner');
    var collection = [];
    var searchStatus;

    ws.onMessage(function (event) {
        console.log('message: ', event);

        messageJson = angular.fromJson(event.data);
        if (messageJson.statusString){
            searchStatus = messageJson.statusString;
        }

        collection.push(angular.fromJson(event.data));
    });

    ws.onError(function (event) {
        console.log('connection Error', event);
    });

    ws.onClose(function (event) {
        console.log('connection closed', event);
    });

    ws.onOpen(function () {
        console.log('connection open');
    });

    // setTimeout(function () {
    //  ws.close();
    // }, 300000)

    return {
        collection: collection,
        searchStatus: searchStatus,
        // status : function () {
            // return ws.readyState;
        // },
        send : function (message) {

            if (angular.isString(message)) {
                ws.send(message);
            } else if (angular.isObject(message)) {
                ws.send(JSON.stringify(message));
            }
        }

    };
});

Thanks!

Upvotes: 3

Views: 138

Answers (1)

Phil
Phil

Reputation: 164832

Because searchStatus: searchStatus in the return object loses its reference when you execute searchStatus = messageJson.statusString;, it will always remain undefined in Messages.

Simply create your factory's return object earlier and update that instead of the individual variables. For example

var ws = $websocket('ws://localhost:8080/portscanner2/scanner'),
    obj = {
        collection: [],
        searchStatus: null,
        send: function(message) { /* no change here */ }
    };

ws.onMessage(function (event) {
    console.log('message: ', event);

    messageJson = angular.fromJson(event.data);
    if (messageJson.statusString){
        obj.searchStatus = messageJson.statusString;
    }

    obj.collection.push(angular.fromJson(event.data));
});

// etc

return obj;

Also, your template should have

Status : {{ Messages.searchStatus }}

Upvotes: 1

Related Questions