在 Firebase 中对项目集合进行建模的正确方法 [英] Correct way to model a collection of items in Firebase

查看:21
本文介绍了在 Firebase 中对项目集合进行建模的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在文档中,我看到很多示例使用索引值作为特定项目的键名的一部分 --- 但我不明白这是如何为数据建模的一致方式.

例如,假设我有一个文章列表:

https://gigablox.firebaseio.com/articles/第1条第2条第三条

当我准备好添加 article4 时,我知道我可以使用:

var length = Object.keys($scope.articles).length;

并且使用 AngularFire 0.5.0 我可以保存它:

var name = '文章' + 长度 + 1;$scope.articles[name] = $scope.article;$scope.articles.$save(name);

但是如果我:

$scope.articles.$remove('article2');

并使用相同的方法添加另一条记录?我们可能会创建重复的键名.

为了增加一点复杂性,让我们添加一个关系并假设每篇文章都有评论.

在 Firebase 集合中建模此数据的正确方法是什么?

解决方案

请使用 $add 并让 Firebase 自动为您生成按时间顺序排列的列表.

var ref = new Firebase("https://gigablox.firebaseio.com/articles/");$scope.articles = $firebase(ref);$scope.addArticle = function() {$scope.articles.$add($scope.article);}$scope.removeArticle = function(id) {$scope.articles.$remove(id);}

当您调用 $add 时,Firebase 会自动创建键名.您可以使用 ng-repeat 遍历键名:

<div ng-model="article"><a ng-click="removeArticle(key)">移除</a></div>

In the docs I see a lot of examples using index values as a part of the key name for a particular item --- but I don't understand how this is a consistent way to model your data.

For example let's say I have a list of articles:

https://gigablox.firebaseio.com/articles/
article1
article2
article3

When I'm ready to add article4 I know I can use:

var length = Object.keys($scope.articles).length;

And using AngularFire 0.5.0 I can save it with:

var name = 'article' + length + 1;
$scope.articles[name] = $scope.article;
$scope.articles.$save(name);

But what happens if I:

$scope.articles.$remove('article2');

And add another record using the same approach? We're likely to create duplicate key names.

To add a little complexity, let's add a single relationship and say that each article has comments.

What is the correct way to model this data in a Firebase collection?

解决方案

Please use $add and let Firebase automatically generate chronologically ordered lists for you.

var ref = new Firebase("https://gigablox.firebaseio.com/articles/");
$scope.articles = $firebase(ref);

$scope.addArticle = function() {
  $scope.articles.$add($scope.article);
}

$scope.removeArticle = function(id) {
  $scope.articles.$remove(id);
}

Firebase automatically creates key names when you call $add. You can iterate over the key names using ng-repeat:

<div ng-repeat="(key, article) in articles">
  <div ng-model="article"><a ng-click="removeArticle(key)">Remove</a></div>
</div>

这篇关于在 Firebase 中对项目集合进行建模的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆