有没有办法从firebase获取随机记录,如下所示:
{
"-JbmopNnshefBT2nS2S7" : {
"dislike" : 0,
"like" : 0,
"post" : "First post."
},
"-JbmoudijnJjDBSXNQ8_" : {
"dislike" : 0,
"like" : 0,
"post" : "Second post."
}
}
Run Code Online (Sandbox Code Playgroud)
我使用此代码来解决问题,但它下载了所有记录,因此如果DB更大,我的应用程序将非常慢:
HTML代码:
<div ng-controller="RandomCtrl">{{RandomPost.post}}</div>
Run Code Online (Sandbox Code Playgroud)
JS代码:
var app=angular.module('App', ['firebase']);
app.controller('RandomCtrl', function($scope, $firebase){
var ref = new Firebase("https://ind.firebaseio.com/");
var sync=$firebase(ref);
$scope.messages = sync.$asArray();
$scope.GetRandomPost=function(){
return $scope.RandomPost=$scope.messages[Math.floor(Math.random()*$scope.messages.length)];
};
$scope.GetRandomPost();
});
Run Code Online (Sandbox Code Playgroud)