2015-05-19 133 views
0

我的任務是從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

+1

偏題:「Lottery」 – isherwood

回答

0

假設你的邏輯爲seconds是正確的,如何只解決從getNumber()功能的對象,而不是簡單的數量,如:

deferred.resolve({ number: $scope.randomNumber, seconds: $scope.seconds/1000 }); 

然後在您的標記中:

<span ng-repeat="nr in resultNumbers track by $index"> 
    <h1>{{ nr.number }} - {{ nr.seconds }}</h1>   
</span> 

您更新的CodePen

這就是說,某些邏輯似乎不正確。

+0

你說得對秒鐘的邏輯是正確的。兩個括號丟失。所以,不是這樣的:$ scope.seconds = 1000 * Math.floor(Math.random()*($ scope.maxSeconds - $ scope.minSeconds + 1))+ $ scope.minSeconds;但是像這樣:$ scope.seconds = 1000 *(Math.floor(Math.random()*($ scope.maxSeconds - $ scope.minSeconds + 1))+ $ scope.minSeconds); – Davo

相關問題