我的任務是從1到100生成3個隨機數。每個數字都需要在2-5秒內生成。如何同時顯示3個隨機數和時間間隔
生成後,每個數字(連同其生成的秒數)都應該出現在屏幕上。所以,一個接一個(並非全部同時)數字應該出現在屏幕上。
我設法得到屏幕上的三個隨機數字,但我無法獲得屏幕上顯示的秒數以及相應的數字。
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body ng-app="Lotery">
<div class="container" ng-controller="MainController">
<div class="row">
<div class="col-lg-12">
<h1>Three random numbers from {{ bottomNumber }} to {{ topNumber }}<small> (each in {{ minSeconds }} - {{ maxSeconds }} seconds)</small></h1>
<button class="btn btn-default" ng-click="firePromise()">Click to get the numbers</button>
<span ng-repeat="nr in resultNumbers track by $index">
<h1>{{ nr }} </h1>
</span>
</div>
</div>
</div>
</body>
</html>
angular.module('Lotery',[]);
angular.module('Lotery').controller('MainController', function($scope, $q) {
$scope.topNumber = 100;
$scope.bottomNumber = 1;
$scope.maxSeconds = 5;
$scope.minSeconds = 2;
function getNumber(){
var deferred = $q.defer();
setTimeout(function(){
$scope.randomNumber = Math.floor(Math.random() * ($scope.topNumber - $scope.bottomNumber + 1)) + $scope.bottomNumber;
$scope.seconds = 1000 * Math.floor(Math.random() * ($scope.maxSeconds - $scope.minSeconds + 1)) + $scope.minSeconds;
if(angular.isNumber($scope.randomNumber)){
deferred.resolve($scope.randomNumber);
} else {
deffered.reject('Error');
}
}, $scope.seconds);
return deferred.promise;
};
$scope.firePromise = function(){
$scope.resultNumbers = [];
var promise = getNumber();
promise.then(function(success){
$scope.resultNumbers.push(success);
return getNumber();
}).then(function(success){
$scope.resultNumbers.push(success);
return getNumber();
}).then(function(success){
$scope.resultNumbers.push(success);
});
};
});
見我的筆:http://codepen.io/M4i4/pen/EjyMdY
偏題:「Lottery」 – isherwood