2016-04-11 55 views
-1

我想在URL中查詢字符串的值上運行angular.forEach函數。Angular for each function troublebles

考慮以下幾點:

domain.com?quote=10&quote=20

否則$scope.selectedQuotes = $stateParams.quote;按預期方式工作,並輸出["10", "20"],創建一個數組。

但具有相同功能的上:

domain.com?quote=10

此輸出「10」作爲一個字符串,並運行在foreach上每個字符。

下面是完整的代碼:

$scope.selectedQuotes = $stateParams.quote; 
console.log($scope.selectedQuotes); 

angular.forEach($scope.selectedQuotes, function(quote){ 
} 

所以現在的問題是,你如何獲得它,所以它總是類值作爲一個數組?

+0

這似乎是預期的行爲給我。你必須檢測它是一個數組還是一個字符串,並相應地採取行動。 –

+0

@KevinB文檔已經陳述相同..我已經添加它作爲答案 –

回答

1

OK ...添加:

params: { 
    quote: { array: true } 
} 

爲了解決這個狀態控制器。

+0

它真的工作,通過添加它..我懷疑.. –

+0

是的。現在完美運作。 –

1

Docs已經說明

如果爲單個參數的多個值存在於URL (例如:?/富巴= 1名&巴= 2 &巴= 3),則值是映射到數組 (例如:{foo:['1','2','3']})。但是,如果只有一個值爲 (例如:/ foo?bar = 1),則該值被視爲單個值 (例如:{foo:'1'})。

因此,即使您的變量類型爲array: true內部狀態,就像您有quote狀態參數爲數組一樣。當單個值出現反對quote,這將被視爲string'10'

-1
if(Array.isArray($scope.selectedQuotes)){ 
//itar with angular.forEach 
    } else{ 
    $scope.selectedQuotes=[$scope.selectedQuotes] 
    // then itar with angular.forEach 
} 
0

您可以用map()做到這一點:

$scope.selectedQuotes = $stateParams.quote; 
console.log($scope.selectedQuotes); 

angular.forEach($scope.selectedQuotes, function(quote){ 
    return quote.map(function(newArray) { 
     return newArray; 
    }); 
}