编程语言
首页 > 编程语言> > javascript-在ng-Repeat中随机化数组

javascript-在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>

注意:不需要按钮进行随机化.该按钮仅跳至下一个国家/地区幻灯片,但每次都应更改城市名称.

解决方法:

您可以应用randomize()函数来选择城市中的随机城市:

<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>

标签:angularjs,random,angularjs-ng-repeat,arrays,javascript
来源: https://codeday.me/bug/20191026/1933872.html