Javascript 角度控制器不显示来自JSON的数据
我将Angular和TingoDB Mongo内部节点Webkit用于单页应用程序。然而,我有一个奇怪的问题,我一直无法解决 当我使用object literal选项2时,数据在html页面中正确显示。但是,更改代码以从数据库选项1返回数据时,结果不会显示在html页面上。我已将这两种类型的数据转换为JSON字符串以证明一致性,然后使用angular.fromJSON返回一个对象。这两个方法在console.log中返回相同的JSON字符串,在任何人询问之前,我已经注释掉了选项1或选项2,因此这两个方法都不会同时运行 我已将基于TingoDB传递的数据的JSON字符串复制到console.log中,并将其重新输入下面的代码中,以确保在不更改任何其他代码的情况下,两个版本的数据之间不存在差异,但问题仍然存在 有人能解释为什么会发生这种情况以及如何解决它吗Javascript 角度控制器不显示来自JSON的数据,javascript,json,angularjs,mongodb,tingodb,Javascript,Json,Angularjs,Mongodb,Tingodb,我将Angular和TingoDB Mongo内部节点Webkit用于单页应用程序。然而,我有一个奇怪的问题,我一直无法解决 当我使用object literal选项2时,数据在html页面中正确显示。但是,更改代码以从数据库选项1返回数据时,结果不会显示在html页面上。我已将这两种类型的数据转换为JSON字符串以证明一致性,然后使用angular.fromJSON返回一个对象。这两个方法在console.log中返回相同的JSON字符串,在任何人询问之前,我已经注释掉了选项1或选项2,因此这
var app = angular.module('myApp', []);
var Engine = require('tingodb')(),
assert = require('assert');
var db = new Engine.Db('./db', {});
var collection = db.collection("clean.db");
app.controller('tingoDataCtrl', ['$scope', function($scope) {
function getData(callback) {
//Option 1
collection.find().toArray(function(err, docs){
callback (JSON.stringify(docs));
});
//Option 2
var docs = [
{name:"tingo1", description:"56",_id:2},
{name:"tingo2", description:"33",_id:3},
{name:"tingo3", description:"22",_id:4},
{name:"tingo4", description:"76",_id:5},
{name:"tingo5", description:"99",_id:6}
];
callback (JSON.stringify(docs));
}
function info(b) {
// I'm the callback
console.log(b);
$scope.items = angular.fromJson(b)
}
getData(info);
}]);
还有Html
<body ng-app="myApp" id="main">
<div class="page page-data ng-scope">
<section class="panel panel-default" ng-controller="tingoDataCtrl">
<div class="panel-heading"><span class="glyphicon glyphicon-th"></span> Tingo Data</div>
<table class="table">
<thead>
<th class="col-md-4">
Name
</th>
<th class="col-md-8">
Description
</th>
<th class="col-md-8">
ID
</th>
<th></th>
<tr>
</tr>
</thead>
<tbody>
<!-- <tr class="reveal-animation" ng-repeat="item in items | filter:query"> -->
<tr ng-repeat="item in items | filter:query">
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item._id}}</td>
</tr>
</tbody>
</table>
</section>
</div>
<script src="js/tingo_problem.js"></script>
</body>
TingoDB是一个异步API,它将在后台工作,而不会停止您的应用程序。这意味着同步代码没有时间等待答案,而作为回报,它给出了未定义的答案 在您的例子中,您已经完成了一个异步调用,并且它正确地返回了内存的答案,但是太晚了,DOM已经被更新为undefined,即使您的javascript有数据try console.log来查看它是否存在 Angular有一种方法可以强制使用控制器的新元素再次更新DOM。它被称为$apply。使用它来避免意外行为的最佳方法是:
function info(b) {
// I'm the callback
console.log(b);
$scope.items = angular.fromJson(b);
if (!$scope.$$phase) {
$scope.$apply(); //forces update the view
}
}//$scope is NECESARY to be defined in the controler, avoid using it with "ControlerAs"