AngularJS: How to get JSON object key

I'm not sure if this is generally related to AngularJS, and if it is just JSON.

Anyway, let's say we have the following JSON:

$scope.dataSets = { "names": ["Horace", "Slughorn", "Severus", "Snape"], "genders": ["Male", "Female"] } 

Now I use the ng-repeat directive to print above:

 <div ng-repeat="data in dataSets> //Continue readig to know what I am expcting here </div> 

What I expect in the <div></div> tags is to type "name" and "gender". That is, I want to print JSON keys. I have no idea what keys are, how anything can be in them. How can i do this?

+47
json angularjs
Mar 20 '13 at 14:00
source share
4 answers

As stated in the document:

(key, value) in the expression - where the key and value can be any identifiers identifiable by the user, and the expression can be a scope expression that allows the collection to be counted.

 <div ng-repeat="(key, data) in dataSets"> {{key}} </div> 
+91
Mar 20 '13 at 14:13
source share

to access the Json key-value pair from the internal controller in AngularJs .

 for(var keyName in $scope.dataSets){ var key=keyName ; var value= $scope.dataSets[keyName ]; alert(key) alert(JSON.stringify(value)); } 
+8
Oct. 14 '15 at 8:34
source share

if dataSets is an array and not an object that you first need to ng-repeat the elements of the array and then a key or value.

 <div ng-repeat="item in dataSets"> <div ng-repeat="(key, value) in item"> {{key}} {{value}} </div> </div> 

only my 2 cents.

+2
Apr 23 '15 at 13:44 on
source share

For each dataset in the datasets, type a key, and then iterate over the individual elements:

 <div ng-repeat="(key, dataSet) in dataSets"> <div>{{key}}</div> <div ng-repeat="value in dataSet"> {{value}} </div> </div> 

{{dataset}} can also be displayed at a time, the array will be displayed as a comma-separated list of values.

+1
Jun 29 '16 at 12:48
source share



All Articles