来自二级对象的 Firebase $id

Firebase $id from second level Object

所以我在 firebase 中有这个例子

clients {
   //clients with unique keys {
       invoices: {
         // Invoices with unique Keys
       }
   }
}

我正在 return 像这样用一个 ref 处理所有这些:

.controller('singleClientController', function($scope, $firebaseObject, fbUrl, $routeParams) {

    var id = $routeParams.id;

    var singleRef = new Firebase(fbUrl+'/clients/'+id);
    var client = this;

    client.details = $firebaseObject(singleRef);

})

所以在我的 html 中,我正在尝试 return 客户和发票的 $id。我可以让客户对 {{client.details.$id}} 没有问题,但是当我尝试对发票 ID {{invoice.$id}} 做同样的事情时,我什么也没得到。

发票通过 foreach 显示,如下所示:

<tr ng-repeat="invoice in client.details.invoices">
     <td>
         <a href="#/invoices/details/{{invoice.$id}}/{{client.details.$id}}">
            {{invoice.settings.number}}
         </a>
     </td>
     ...
</tr>

是因为发票在客户内部吗?如果是这样,您如何 return 发票的 ID?这让我发疯!请帮忙!

为了更好地理解我的 firebase 设置,这里是我正在谈论的内容的屏幕截图。

tl;dr - 在 Firebase 中,拥有扁平数据结构是理想的。

JSBin Example

在您的情况下,您的发票嵌套在客户下。

{
   "clients": {
      "1": {
         "name": "Alison",
         "invoices": {
            "0001": {
              "amount": 500
              "paid": true
            }
         }
      }
   }
}

这感觉很自然,因为发票在适当的客户下很好地分组。但是,这可能会导致与 Firebase 同步数据时性能不佳。 Firebase 读取节点下的所有数据。

这意味着您每次阅读 /clients/1 时,您还会通过网络下载发票。即使您只需要客户的名字,您也可以获得发票。

解决方案是扁平化你的数据结构。

{
   "clients": {
      "1": {
        "name": "Alison"
      }
   },
   "clientInvoices": {
     "1": {
        "0001": {
          "amount": 500
          "paid": true
        }
     }
   }
}

这里要掌握的重要部分是共享密钥

在此示例中,密钥是 1。这是为了简单起见。实际上,您可能会使用 .push() id。

通过使用此模式,您仍然可以通过简单地知道客户的密钥来检索客户的所有发票。这也使客户与发票脱钩。

作为一个额外的好处,您的控制器代码和 ng-repeat 会更容易。

在您的情况下,您应该将发票从 $firebaseObject 切换到 $firebaseArray。我们甚至可以创建一个帮助工厂,通过客户的 ID 获取发票。

.factory('invoices', function(fbUrl, $firebaseArray) {
   return function(clientId) {
      var ref = new Firebase(fbUrl).child('clientInvoices').child(clientId);
      return $firebaseArray(ref);
   }
})

// While we're at it, lets create a helper factory for retrieving a
// client by their id
.factory('clients', function(fbUrl, $firebaseObject) {
    return function(clientId) {
       var ref = new Firebase(fbUrl).child('clients').child(clientId);
       return $firebaseObject(ref);
    }
})

现在将辅助工厂注入您的控制器并使用 $routeParams.id 检索客户的发票:

.controller('singleClientController', function($scope, $routeParams, invoices, clients) {

    $scope.client = clients($routeParams.id);
    $scope.clientInvoices = invoices($routeParams.id);

})

现在将它绑定到您的模板是一件轻而易举的事:

<tr ng-repeat="invoice in clientInvoices">
     <td>
         <a href="#/invoices/details/{{invoice.$id}}/{{client.$id}}">
            {{invoice.settings.number}}
         </a>
     </td>
     ...
</tr>