yavg
yavg

Reputation: 3051

How can I show my json keys in an ng-repeat?

I have an array with 3 elements. Each element has a different key. How can I do to show only the name of the keys?

<div ng-app="myApp">
    <div ng-controller="myController">
      <div ng-repeat="item in names">
        {{item}}

      </div>
    </div>
</div>

var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {

  $scope.names=
  [
    {"joe":1},
    {"pablo":2},
    {"greic":3}
  ]

 //output should be:
 //joe
 //pablo
 //greic

});

http://jsfiddle.net/8wq4qmh0/

Upvotes: 0

Views: 52

Answers (1)

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

You can pull out key and values with (x,y) syntax. But since it's an array of objects, you need another ng-repeat.

var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
  $scope.names = [{"joe": 1},{"pablo": 2},{"greic": 3}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
    <div ng-repeat="item in names"> <!-- pull object from the array -->
      <div ng-repeat="(key, val) in item"> <!-- pull key and value from the object -->
        {{key}}
      </div>
    </div>
  </div>
</div>

Upvotes: 2

Related Questions