收到新数据时重新加载角表

时间:2017-08-03 14:34:31

标签: javascript angularjs html-table

当收到来自websocket的数据时,我需要填充一个角度表:我试过:

<div ng-controller="MyCtrl" ng-app="myapp">
        <table ng-table="commentsTable">
            <tr ng-repeat="item in obj track by $index">
            <td class="plantCell">{{item.nome}}: </td>
            <td class="statusCell">{{item.status}}</td>
            <td class="statusCell">{{item.testo}}</td>
        </tr>
        </table>
        </div>
<script>
    var app=angular.module('myapp', []);
    var printOperation;
    function GetFromLocalStorage(key) {
        var items=localStorage.getItem(key);
        console.log(items);
        if (items===null){
            console.log("item null");
            return null;
        } else {
            if (typeof items!= "string") {items = JSON.stringify(items);}
                    return items;
        }
    }
    app.controller('MyCtrl',    
                function ($scope) {
                    $scope.printComments=function (){
                        $scope.obj=GetFromLocalStorage("AllComments");
                        console.log("ricevo evento e ricarico tabella");
                        console.log($scope.obj);
                        //$scope.commentsTable.reload();
                    }

                    console.log("assegno print operation");
                    printOperation=$scope.printComments;
                }
            );  
            var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
            var eventer = window[eventMethod];
            var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
            eventer(messageEvent,function(e) {
                console.log("ricevo messaggio");
                printOperation();
            },false);
<script>
  

未捕获的TypeError:无法读取未定义的属性'reload'       at $ scope.printComments((index):68)       在(指数):80

1 个答案:

答案 0 :(得分:1)

如果您使用的是ngTable,则应将其注入您的应用模块,例如angular.module("myapp", ["ngTable"]);

更新:因此,在讨论了问题并获得更多上下文后,我可以假设数据在事件监听器中的AngularJS上下文之外被修改,因此视图不会显示更新的值,所以我假设用$applyAsync包裹printOperation应该有所帮助:

printOperation = $scope.$applyAsync($scope.printComments);

此外,我认为逻辑应该在一个地方 - 例如控制器内部,因为它将使代码更易读和可维护。