2014-11-24 100 views
1

我想在Angular中使用while循環。 如果我在while循環中使用alert,它會給出相同的數量輸出。但我刪除alert,數量不同。那麼我的代碼有什麼問題。While循環在angularjs中無法正常工作

var quantity= $scope.quantity; 
var i=0; 
while(i< quantity) 
     { 
         order.createOrderLineItem(localStorage.getItem("orderID"), itemStr, undefined, $scope.errorCallback) 
       .success(function(data){ 
       $scope.lineItemID = data.id; 

       alert("i:"+i); 
       var orderLineItemData = {}; 
       if($scope.cusNote == "") 
       { 
        var existedNote = data.note || ""; 
        orderLineItemData = { 
         "unitQty": $scope.quantity, 
         "note": existedNote, 
        }; 

        //if adding taxRates 0, clover will returns error 
        if($scope.taxRates !== 0) { 
         orderLineItemData.taxRates = $scope.taxRates; 
        } 
       } 
       else 
       { 
        var customerNote = ""; 

        if(data.note != undefined && data.note != null) customerNote = data.note; 

        customerNote = customerNote + "#order-request-["; 
        customerNote = customerNote + $scope.cusNote; 
        customerNote = customerNote + "]"; 
        customerNote = customerNote.replace(/\\/g, '\\\\'); 
        customerNote = customerNote.replace(/\"/g, '\\"'); 

        console.log("customerNote:" + customerNote); 

        orderLineItemData = { 
         "unitQty":$scope.quantity, 
         "note": customerNote, 
         "taxRates": $scope.taxRates 
        } 
       } 

       order.updateOrderLineItem(localStorage.getItem("orderID"), $scope.lineItemID, JSON.stringify(orderLineItemData), undefined, $scope.errorCallback) 
        .success(function(data){ 
         if($scope.modCount == 0) 
         { 
          location.href = "/" + $routeParams.slug; 
         } 

         $scope.addModifierItem($scope.lineItemID); 
        }); 
      }); 
      i++; 
     } 

那麼我該如何糾正這段代碼呢?

+2

似乎在同步循環內使用異步調用...結果是意外的。 – Kinnza 2014-11-24 10:40:57

+0

那麼,我該如何在其中進行更改 – 2014-11-24 10:46:34

+0

從代碼示例中不清楚,但它看起來好像要以串行方式運行所有請求,而不是並行運行。是這樣嗎? – 2014-11-24 11:34:50

回答

0

我不確定,但,警報可能是原因。你可以嘗試使用console.log("i:"+i);而不是警報。由於彈出窗口而使用警報時,瀏覽器可能會中斷。

--Edited--

這是你需要落實到你的應用程序的服務。你需要在你的成功,通知該服務,這將觸發任何遵守通知

app.service('checkService',['$q',function($q){ 
     var checkRequest = $q.defer(); 

     this.notifyRequestIsDone= function(){ 
      checkRequest .notify(); 
     }; 

     this.observeRequestStatus = function(){ 
      return checkRequest .promise; 
     }; 
    }]); 

這裏之後所實行的是觀察例子的代碼上面添加到您的控制器,你需要開始增加你的價值請求已完成

checkService.observeRequestStatus().then(null,null,function(){ 
    //... Your code 
}); 
+0

我試過了,但沒有幫助 – 2014-11-24 11:16:01

+0

我看到你正在申請一個數據並且在成功上做了一些工作。你應該注意到,如果你正在調用一個http請求,服務器返回將會有一個延遲。所以如果沒有提示,javascript將不會等待返回「i」的增量,但如果添加了提醒,它將停止js,直到您彈出按鈕爲止,因此這會導致請求返回的時間間隔。您可以播放或使用延遲來正確獲得成功。我希望這會幫助你 – 2014-11-24 11:33:26

+0

如何使用延遲 – 2014-11-25 05:45:48