如何遍历Angular JSON对象

3
我已经创建了一个nodejs应用程序,该程序将读取我mongo Db中的所有数据库,在控制台上可以实现。但是,当我尝试将数据解析为json对象并将其显示到屏幕上时,我无法使信息显示。希望有人能帮助我找出原因或告诉我我做错了什么。谢谢
app.js
// listen for get request, aka transfers the info in mongo to client
app.get('/databases', function (req, res) {
    console.log("-- recived GET request --"); 
    db.open(function(err, db) {

      // Use the admin database for the operation
      var adminDb = db.admin();

      // List all the available databases
      adminDb.listDatabases(function(err, dbs) {
        assert.equal(null, err);
        assert.ok(dbs.databases.length > 0);
        console.log(dbs);
        res.json(dbs); 
        db.close();
      });
    });
}); 

controller.js

var app = angular.module('myApp', []);

app.controller('customersCtrl', function($scope, $http) {
    console.log("controller connected");

function refresh(){ 
// create route 
$http.get('/databases').success(function(response) {
    console.log("recived data requested");
    $scope.databases = response; 
  });
}

// Call refresh to get req
refresh(); 

});// Controller 

index.html

<body>

<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul>
  <li ng-repeat="contact in databases">
    {{ contact }}
  </li>
</ul>
 <button type="button" onclick="hitMe()">Click Me!</button> 
</div>

</body>

enter image description here


你尝试过添加另一个ng-repeat,然后通过contract.names或contact.Sizeof进行重复吗? - Andrew Kralovec
你能够逐步执行你的代码并查看响应结果吗?在某些情况下,你需要从响应中获取数据属性:$scope.databases = response.data;(https://docs.angularjs.org/api/ng/service/$http#general-usage - 响应对象) - vidriduch
是的,安德鲁,我尝试过了,但不起作用。punov 给出了正确的答案。 - AJ_
2个回答

2

看起来您需要遍历databases.databases对象。 只要$scope.databases是:

{
 databases: [],
 totalSize: ..,
 ..
}

您需要在页面上使用以下ng-repeat:
<ul>
  <li ng-repeat="contact in databases.databases">
    {{ contact.name }}
  </li>
</ul>

哦,谢谢。这个可行。那么 'databases.databases' 是什么意思? - AJ_
我刚刚注意到,在您的数据库($scope.databases = response)对象中,当您在控制台中查看它时,您有一个“databases”字段。而且只有这个字段包含联系人数组。 - punov

0

正如安德鲁所说,在您的HTML代码中尝试使用contact.name。

“contact”本身将是整个对象。您必须指定要使用对象的哪个部分。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接