gpt4 book ai didi

javascript - 如何以 Angular View 显示数组中的随机对象?

转载 作者:行者123 更新时间:2023-11-28 18:04:39 24 4
gpt4 key购买 nike

我尝试将数组中的随机对象的信息显示到 DOM 中的 NG-Repeat 情况中:

首先,这是 Controller 的代码,它简单地创建数组并填充对象:

// 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 代码中。

此外,我想确保如果我的数组中只有一个对象,它总是显示它。

要做什么?

最佳答案

我认为你在这里不需要 ng-repeat,因为你只想显示一项(或者如果没有项则什么也不显示),所以将 ng-repeat 替换为:

ng-if="businessAd"

您可以将其放入 Controller 中以获得随机添加。

        //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;
}

关于javascript - 如何以 Angular View 显示数组中的随机对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42912178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com