Angular JS - 迭代从Firebase数据库获取的对象数组

时间:2017-07-12 01:16:09

标签: javascript angularjs firebase firebase-realtime-database

我正在构建一个从Firebase数据库获取其对象的应用程序。问题是当我尝试迭代我得到的东西时,它没有显示任何东西。但是,当我要求通过console.log显示它时,它就在那里! 我想这是因为HTTP方法及其承诺。但我还没弄清楚如何解决它。有人可以帮我理解吗?

HTML:

<table class="table">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Description</th>
      <th>Price</th>
      <th>Options</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="profile in profiles">
      <td>{{profile.value.id}}</td>
      <td>{{profile.value.name}}</td>
      <td>{{profile.value.description}}</td>
      <td>{{profile.value.price | currency}}</td>
      <td>
        <button type="button" class="btn">Edit</button>
        <button type="button" class="btn btn-danger">Delete</button>
      </td>
    </tr>
  </tbody>
</table>

Controller.js

App.controller("adminController", function($scope) {
  console.log("running");

  var profiles = new Array;

  var query = firebase.database().ref("profiles").orderByKey();

  query.once("value")
  .then(function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
        var key = childSnapshot.key;
        var childData = childSnapshot.val();

        profiles.push({
          key: key,
          value: JSON.parse(childData)
        })
    });
    console.log(profiles);
  });
}

1 个答案:

答案 0 :(得分:2)

您需要在控制器上使用 $scope.profiles

App.controller("adminController", function($scope) {
  console.log("running");
  $scope.profiles = [];
  var query = firebase.database().ref("profiles").orderByKey();
  query.once("value")
  .then(function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
        var key = childSnapshot.key;
        var childData = childSnapshot.val();
        $scope.profiles.push({
          key: key,
          value: JSON.parse(childData)
        })
    });
    console.log($scope.profiles);
  });
}