当收到来自 websocket 的数据时,我需要填充 Angular 表:我尝试过:
<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>
Uncaught TypeError: Cannot read property 'reload' of undefined at $scope.printComments ((index):68) at (index):80
最佳答案
如果您使用 ngTable
你应该将它注入(inject)到你的应用程序模块中,如 angular.module("myapp", ["ngTable"]);
.
更新:因此,在讨论了这个问题并获得了更多相关上下文之后,我可以假设数据是在事件监听器中的 AngularJS 上下文之外修改的,因此 View 不会显示更新的值,因此我假设包装printOperation
与 $applyAsync
应该有帮助:
printOperation = $scope.$applyAsync($scope.printComments);
此外,我认为逻辑应该位于一个地方 - 例如在 Controller 内部,因为它将使代码更具可读性和可维护性。
关于javascript - 收到新数据时重新加载 Angular 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45487278/