所以我在firebase中有这个
clients {
//clients with unique keys {
invoices: {
// Invoices with unique Keys
}
}
}
我用一个引用将所有这些返回,如下所示:
.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中,我试图同时返回客户和发票的
$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>
是因为发票在客户内部吗?如果是这样,您将如何返回发票的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。通过使用这种模式,您仍然可以通过仅知道客户的密钥来检索客户的所有发票。这也使客户与发票脱钩。
另一个好处是,您的 Controller 代码和
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);
}
})
现在将帮助程序工厂注入(inject)到您的 Controller 中,并使用
$routeParams.id
检索客户的发票:.controller('singleClientController', function($scope, $routeParams, invoices, clients) {
$scope.client = clients($routeParams.id);
$scope.clientInvoices = invoices($routeParams.id);
})
现在将其绑定(bind)到您的模板变得轻而易举:
<tr ng-repeat="invoice in clientInvoices">
<td>
<a href="#/invoices/details/{{invoice.$id}}/{{client.$id}}">
{{invoice.settings.number}}
</a>
</td>
...
</tr>