【问题标题】:Cannot bind data from AngularJS factory无法从 AngularJS 工厂绑定数据
【发布时间】:2015-11-26 05:21:06
【问题描述】:

我是 AngularJS 的新手,并以 webSocket 示例作为我的应用程序的基础https://github.com/AngularClass/angular-websocket/tree/master/example 应用程序应该从 webSocket 获取 JSON 数据并填充 UI。示例包含带有集合变量的工厂,并且绑定在 HTML 模板上给出结果,但是当我添加 searchStatus 变量时,我在 UI 上看不到它的自动更新(绑定)。为什么?

    <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 脚本代码

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));
            }
        }

    };
});

谢谢!

【问题讨论】:

  • 你为什么使用SimplePortScannerController as simpleCtrl却引用$scope
  • 是的,对,我会更新,只留下 SimplePortScannerController,没有 as。

标签: javascript angularjs factory


【解决方案1】:

因为在执行searchStatus = messageJson.statusString; 时,返回对象中的searchStatus: searchStatus 失去了它的引用,所以它在Messages 中将始终保持undefined

只需提前创建工厂的返回对象并更新它而不是单个变量。例如

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;

另外,你的模板应该有

Status : {{ Messages.searchStatus }}

【讨论】:

  • 谢谢,它有效。只是在第一行将昏迷改为分号。为什么 searchStatus 失去参考,但收集没有?我应该在某处阅读吗?这是因为没有创建集合,而是推送了集合吗?
  • @Pavlo 是的,就是这样。 collection 变量永远不会重新分配,从而保持引用。此外,您不必替换逗号;我的答案是正确的语法
  • 是的,它也适用于逗号。我刚刚意识到两者(逗号或分号)在这里实际上意味着相同。我错过了,因为从不使用这样的语法来创建多个变量。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
相关资源
最近更新 更多