0

我在 Node Webkit 中使用 Angular 和 TingoDB (Mongo) 来实现单页应用程序。但是我有一个奇怪的问题,我一直无法解决。

当我使用对象文字(选项 2)时,数据在 html 页面中正确显示。但是,更改代码以从数据库返回数据(选项 1)结果不会出现在 html 页面上。我已将两种样式的数据转换为 JSON 字符串以证明一致性,然后使用 angular.fromJSON 返回一个对象。两种方法都在 console.log 中返回相同的 JSON 字符串,在有人问我之前,我已将选项 1 或选项 2 注释掉,因此两者都不会同时运行。

我已将基于从 TingoDB 传递的数据的 JSON 字符串复制到 console.log 中,并将其重新输入到下面的代码中,以确保在不更改任何其他代码的情况下,两个版本的数据之间不存在差异,但问题仍然存在持续存在。

任何人都可以阐明为什么会发生这种情况以及如何解决它?

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>
4

1 回答 1

0

TingoDB 是一个异步 API,它将在后台运行而无需停止您的应用程序。这意味着同步代码没有时间等待答案,作为回报,它给出了未定义的答案。

在您的情况下,您已经完成了一个异步调用,并且它正确地返回了内存的答案,但是为时已晚,即使您的 javascript 有数据,DOM 也已经更新为 undefined (尝试 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"
于 2015-02-23T13:48:01.757 回答