2013-08-23 17 views
21

我有一個像下面Angular JS - angular.forEach - 如何獲取對象的關鍵?

{ 
    "txt_inc_Application": { 
     "EWS": true, 
     "EWindow": true 
    }, 
    "txt_inc_IncidentType": { 
     "Brand Damage": true, 
     "Internal failure": true 
    } 
} 

,我使用angular.forEach得到的值

$scope.filterFormula=function() { 
    angular.forEach($scope.filters, function(filterObj , filterIndex) { 
     angular.forEach(filterObj, function(value , key) { 
      console.log(value+"--"+key) 
     }) 
    }) 
} 

我怎樣才能在迴路中得到「txt_inc_Application」和「txt_inc_IncidentType」 JSON對象?

當在下面的html中調用角函數時,爲什麼它會執行兩次?

{{filterFormula()}} 

enter image description here

+0

嘗試$ scope.filterFormula =功能(){0} {0} {0}}}}} angular.forEach($ scope.filters,function(filterObj,filterIndex){ angular.forEach(filterObj,function(value,key){ console.log(filterIndex) }) }) } – TyrHunter

+1

每個應用摘要循環至少調用一次綁定。 AngularJS不斷檢查所有綁定,直到一個循環中沒有任何變化。因此,如果它檢查'filterFormula',並且模型中的某些內容在同一週期中發生變化,它將會再次被調用!然後再次!然後再次!最多10次,直到出現錯誤「達到10 $摘要迭代」。 –

+0

謝謝。傻我。我不知道爲什麼我忽略了這一點。此外任何想法爲什麼filterFormula函數執行兩次?我可以看到console .log被打印兩次。 – Saravanan

回答

46

forEach迭代器中的第一個參數是所述值和第二個是對象的鍵。

angular.forEach(objectToIterate, function(value, key) { 
    /* do something for all key: value pairs */ 
}); 

在您的例子中,外層的foreach居然是:

angular.forEach($scope.filters, function(filterObj , filterKey) 
2
var obj = {name: 'Krishna', gender: 'male'}; 
angular.forEach(obj, function(value, key) { 
    console.log(key + ': ' + value); 
}); 

產生的obj屬性各自的價值:

name: Krishna 
gender: male 
+2

也提供代碼的解釋。 –

+4

歡迎來到Stack Overflow!雖然這段代碼片段是受歡迎的,並且可能會提供一些幫助,但如果它包含* how *和* why *的解釋](// meta.stackexchange.com/q/114762),它會[大大改進],這將解決問題。請記住,你正在爲將來的讀者回答這個問題,而不僅僅是現在問的人!請編輯您的答案以添加解釋,並指出適用的限制和假設。 –