【问题标题】:How to display a random object from an array in a an angular view?如何在角度视图中显示数组中的随机对象?
【发布时间】: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


【解决方案1】:

我认为您在这里不需要 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;
      }

【讨论】:

  • 你好,它可能是在正确的方式,但它不显示任何东西但是有对象被推送到我的数组中......实际上我有 2 个对象要推送,它们都在推入数组但不显示其中任何一个...
  • 这是在您对控制器实施更改之前吗?如果是的话:$scope.businessAd[0].name 和 $scope.businessAd[0].description 中的内容是什么?
  • 首先,console.log(random) 触发 4 次,我不知道为什么,然后 name 和 desc 的 businessAd[0] 返回:Uncaught TypeError: Cannot read property '0'的未定义。但是console.log(random)实际上显示的是数组中的随机数据,所以存在!
  • 看起来您对控制器进行了更改。你是否?那么您是否对视图进行了更改? ng-if="businessAd" 替换 ng-repeat="businessAd in businessAds" ?
  • 是的,我实际上把它放在了正确的位置:
【解决方案2】:

这听起来像是你可以在控制器中实现的东西,首先想到的是这样的

控制器:

var matchLength = matches50.length;
var randInBound = Math.floor(Math.random() * matchLength) + 1;
$scope.matched = matches50[randInBound];

然后,您应该能够从您的 html 访问该对象并显示它,只要您的数组中至少有 1 个项目,它就会始终为您提供结果

【讨论】:

  • 我认为这永远不会选择matches50[0],如果为空,则在选择matches50[1] 时可能会失败。我认为 Math.floor(Math.random() * matchLength) + 1 总是 >=1
  • 感谢您的帮助,我实际上发现其他答案更适合我的情况!反正我投了赞成票!
猜你喜欢
  • 2022-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 2018-10-19
相关资源
最近更新 更多