在ng-Repeat中随机化一个数组

时间:2017-04-05 12:37:44

标签: javascript angularjs arrays random angularjs-ng-repeat

我有一个对象数组,我使用ng-repeat来迭代。但是,每个对象都有2个属性 - 国家(字符串)和城市(数组)。如何在某些按钮点击或页面刷新时随机化此城市数组。一个例子:

$scope.package = [{
  country: 'Sweden',
  cities: ['aaa', 'bbb']
}, {
  country: 'Sudan',
  cities: ['yyy', 'zzz']
}]

$scope.showNext = function() {
  // shows next slide but randomize the cities
}

<ul>
  <li ng-repeat="pack in package">
    <p>{{pack.country}}</p>
      <span>{{pack.cities}}</span> <!-- cities should be random value from the array -->
  </li>
</ul>
<button ng-click="showNext()"> Next Country </button>

注意:按钮不需要进行随机化。按钮只是跳转到下一个国家/地区幻灯片,但每次都应该洗牌城市名称。

2 个答案:

答案 0 :(得分:2)

您可以应用randomize()功能在city中随机选择cities

<ul>
  <li ng-repeat="pack in package">
    <p>{{pack.country}}</p>
    <span>{{randomize(pack)}}</span> 
  </li>
</ul>

您可以尝试使用以下代码段:

function MyCtrl($scope) {
    $scope.package = [
        {country: 'Sweden', cities: ['aaa', 'bbb']}, 
        {country: 'Sudan', cities: ['yyy', 'zzz']}
    ];

    $scope.randomize = function(country) {
        return country.cities[Math.floor(Math.random() * country.cities.length)];
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="pack in package">
      <p>{{pack.country}}</p>
      <span>{{randomize(pack)}}</span> 
    </li>
  </ul>
</div>

答案 1 :(得分:2)

您可以对随机数据使用随机函数,只为一个随机城市使用limitTo

<强>更新 我已经更新了代码片段,而不是从页面调用随机函数(在页面刷新时会每次调用函数),你可以在页面加载时调用它,当你调用下一个按钮时。

&#13;
&#13;
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.random = function() {
    return Math.random();
  }
  $scope.package = [{
    country: 'Sweden',
    cities: ['aaa', 'bbb', 'ccc']
  }, {
    country: 'Sudan',
    cities: ['xxx', 'yyy', 'zzz']
  }]

  function generateRandom() {
    angular.forEach($scope.package, function(country) {
      country.random = country.cities[Math.floor(Math.random() * country.cities.length)];
    })
  }
  $scope.showNext = function() {
    generateRandom();
    // shows next slide but randomize the cities
  }
  generateRandom();

}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="MyCtrl">
    <ul>
      <li ng-repeat="pack in package">
        <p>{{pack.country}}</p>
        <span>{{pack.random}}</span>
        <!-- <span>{{pack.cities|orderBy:random|limitTo:1}}</span> -->
        <!-- cities should be random value from the array -->
      </li>
    </ul>
    <button ng-click="showNext()"> Next Country </button>
  </div>
</div>
&#13;
&#13;
&#13;