我尝试将数组中随机对象的信息显示到我的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代码中。
此外,我想确保如果我的数组中只有一个对象,它总会显示它。
怎么办?
答案 0 :(得分:2)
我认为你不需要在这里使用ng-repeat,因为你只想显示一个项目(如果没有项目则不需要),所以将ng-repeat替换为:
ng-if="businessAd"
您可以将其放入控制器中以获得随机添加。
//here we scope the array to write in our DOM
var matches50Length = matches50.length;
if(matches50Length > 0){
// get random array index
var random = matches50[Math.floor(Math.random()* matches50.length)];
$scope.businessAd = random;
}
答案 1 :(得分:1)
这听起来像你可以在你的控制器中实现的东西,首先想到的是像这样的东西
控制器:
var matchLength = matches50.length;
var randInBound = Math.floor(Math.random() * matchLength) + 1;
$scope.matched = matches50[randInBound];
然后,从您的HTML中,您应该能够访问此对象并显示它,并且只要数组中至少有1个项目,它就会给您一个结果