在文档中,我看到很多使用索引值作为特定项目的键名称的一部分的示例 --- 但我不明白这是如何以一致的方式对数据进行建模。
例如,假设我有一个文章列表:
https://gigablox.firebaseio.com/articles/
article1
article2
article3
当我准备好添加 article4
时,我知道我可以使用:
var length = Object.keys($scope.articles).length;
使用AngularFire 0.5.0我可以保存它:
var name = 'article' + length + 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-repeat="(key, article) in articles">
<div ng-model="article"><a ng-click="removeArticle(key)">Remove</a></div>
</div>
关于javascript - 在 Firebase 中对项目集合进行建模的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20735728/