【发布时间】:2017-03-20 19:18:02
【问题描述】:
我尝试在我的 DOM 中将一个随机对象的信息从一个数组显示到一个 NG-Repeat 情况:
首先,这里是控制器的代码,它简单地创建数组并用对象填充它:
// We check the businesses in the 500m to display a random wide range ad
// First we get the coordinates of the user
database.once('value', function(snapshot) {
var lat50 = snapshot.val().lat;
var long50 = snapshot.val().long;
var rootRef50 = firebase.database().ref();
var geoFireRef50 = rootRef50.child("geobusiness");
var restaurantsRef50 = rootRef50.child("businessarround");
var geoFire50 = new GeoFire(geoFireRef50);
// Then we make a call for Geofire to check all businesses arround
var geoQuery50 = geoFire50.query({
center: [lat50, long50],
radius: 0.5
});
// This is the array that contains the results below
var matches50 = [];
console.log(matches50);
// Listen to every businesses in our query...
geoQuery50.on("key_entered", function(key) {
// ... and look them up by key ...
restaurantsRef50.child(key).once("value", function(snapshot) {
var restaurant50 = snapshot.val();
matches50.push(restaurant50);
for (var i = 0; i < matches50.length; i++)
if (matches50[i].uid && matches50[i].uid === userId) {
matches50.splice(i, 1);
break;
}
$timeout(function(){
//here we scope the array to write in our DOM
$scope.businessAd = matches50;
// Set a timeout to clear loader, however you would actually call the $ionicLoading.hide(); method whenever everything is ready or loaded.
$timeout(function () {
$ionicLoading.hide();
}, 1000);
})
});
});
HTML 代码:
<div class="content2" ng-repeat="businessAd in businessAds" ng-controller="businessPageController">
<div id="map"></div>
<div class="profile-info">
<!-- *profile-image / image profile -->
<img class="profile-image" src="img/100.jpg">
<!-- *profile-name / name profile -->
<h3 class="profile-name">{{businessAd.name}}</h3>
<!-- *profile-description / description profile -->
<span class="profile-description">
{{businessAd.description}}
</span>
<br /><br />
</div>
</div>
但是,现在,我想随机显示它们,因为它不是列表,而是一个单独的位置。因此,我想将数组中的一个对象随机显示到该 HTML 代码中。
此外,我想确保如果我的数组中只有一个对象,它总是显示它。
怎么办?
【问题讨论】:
-
为什么不取第一个元素
-
好吧,因为它显示半径 500m 范围内的商家广告,我不想显示最近的,我想在这 500m 中随机选择。特别是因为在我将有一个“频率”选项之后,其中一些将在数组中出现多次......
-
我不确定这是否可以尝试使用 Javascript 日期对象和 getMilliseconds() 然后 % array.length
标签: javascript angularjs arrays random