【问题标题】:How can I bind an array of returned Firebase elements to my AngularJS view (via a controller)?如何将返回的 Firebase 元素数组绑定到我的 AngularJS 视图(通过控制器)?
【发布时间】:2026-01-29 21:20:09
【问题描述】:

我的 HTML 是

  <tbody>
    <tr ng-repeat="question in questions">
      <td>
        <a ui-sref="englishDetail({id: question.id})">
          {{ question.id }}
        </a>
      </td>
      <td>{{ question.instruction }}</td>
      <td>{{ question.questionText }}</td>
      <td>{{ question.level }}</td>
      <td>
        <a ui-sref="passageDetail({id: question.passageId})">
          {{ question.passageId }}
        </a>
      </td>
    </tr>
  </tbody>

在我的控制器中,我有

var fbase;

$scope.questions = [];

fbase = new Firebase("https://my.firebaseio.com");

fbase.child("questions").orderByChild("subject").equalTo("english").once("value", function(questionsSnapshot) {
  $scope.questions = [];
  questionsSnapshot.forEach(function(questionSnapshot) {
    $scope.questions.push({
      id: questionSnapshot.key(),
      instruction: questionSnapshot.val().instruction,
      questionText: questionSnapshot.val().questionText,
      level: questionSnapshot.val().level,
      passageId: questionSnapshot.val().passageId
    });
  });
  return $scope.$apply();
});

似乎没有必要遍历返回的对象来实现我想要做的事情。有没有更好/更原生的方式来做到这一点?我在 Firebase 文档网站上查看了假定的 three way data binding,但如果您正在过滤对象,那并没有显示如何操作。

【问题讨论】:

    标签: javascript angularjs firebase


    【解决方案1】:

    Use AngularFire for synchronized collections.

    angular.module('app', ['firebase'])
      .constant('FirebaseUrl', '<my-firebase-app>')
      .service('rootRef', ['FirebaseUrl', Firebase])
      .controller('MyCtrl', MyController);
    
    function MyController($scope, rootRef, $firebaseArray) {
      var ref = rootRef.child('questions');
      // handles $digest loop and synchronizing to an array
      $scope.questions = $firebaseArray(ref);
    }
    

    【讨论】:

    • 我可以将它与过滤一起使用吗?
    • 是的。只需从 ref 进行查询并将其传递到 $firebaseArray。
    最近更新 更多