如何在ng-repeat中显示我的json键?

时间:2018-01-18 14:41:51

标签: angularjs

我有一个包含3个元素的数组。每个元素都有不同的键。如何只显示键的名称?

<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/

1 个答案:

答案 0 :(得分:2)

您可以使用(x,y)语法提取键和值。但由于它是一组对象,因此您需要另一个ng-repeat

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
  $scope.names = [{"joe": 1},{"pablo": 2},{"greic": 3}];
});
&#13;
<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>
&#13;
&#13;
&#13;