lundi 20 mars 2017

How to display a random object from an array in a an angular view?

I try to display information of a random object from an array into a NG-Repeat situation in my DOM :

So firs, here is the code of the controller that simply makes the array and fills it up of objects :

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

      })

    });
  });

The HTML code :

<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"></h3>
                <!-- *profile-description / description profile -->
                <span class="profile-description">
                    
                </span>
        <br /><br />
                </div>
            </div>

However, now, I would like to display them randomly because it is not a list but a single emplacement. Therefore, I would like to randomly display one of the objects from my array into that HTML code.

Moreover, I would like to make sure that if there is only ONE object in my array, it always displays it.

What to do ?




Aucun commentaire:

Enregistrer un commentaire