Zichen Ma
Zichen Ma

Reputation: 987

How to use AngularJS to display an json API the key is two words?

I met a problem which is using AngularJS to display a json file which the key contains two words like this:

items: [
{
period: "2017-05-01",
total: 3901,
eloisa moreira: 142,
william morales: 0,
lenilda carvalho: 0,
anamaris gonzalez: 0,
juliana ambroise: 1,
ana luiza theriault: 622,
teresa daveiga: 0
}]

I use:

 <tr ng-repeat="data in data.items">
                <td>{{data.period}}</td>
                <td>{{data.total}}</td> 
                <!--<td>{{data.eloisa moreira}}</td> -->                  
 </tr>

The first two values are displayed fine, but the third one: {{data.eloisa moreira}} give me error: angular.js:13708 Error: [$parse:syntax] Syntax Error: Token 'moreira' is an unexpected token at column 13 of the expression [data.eloisa moreira] starting at [moreira]. Any one how to resolve this problem?

Upvotes: 0

Views: 59

Answers (2)

Pengyy
Pengyy

Reputation: 38191

if you are intended to show all fields of the object, you can use a inner ng-repeat with (key, value) to avoid redundant code and hardcoding properties of object.

<tr ng-repeat="data in data.items">
  <td ng-repeat="(key, value) in data">{{value}}</td>
</tr>

angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.data = {
      items: [{
        "period": "2017-05-01",
        "total": 3901,
        "eloisa moreira": 142,
        "william morales": 0,
        "lenilda carvalho": 0,
        "anamaris gonzalez": 0,
        "juliana ambroise": 1,
        "ana luiza theriault": 622,
        "teresa daveiga": 0
      }]
    };
  });
.solid {
  border: 1px;
  border-style: solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <table class="solid">
    <tr ng-repeat="data in data.items">
      <!--<td>{{data.period}}</td>
      <td>{{data.total}}</td>
      <td>{{data.eloisa moreira}}</td> -->
      <td ng-repeat="(key, value) in data">{{value}}</td>
    </tr>
  </table>
</div>

Upvotes: 2

austinbruch
austinbruch

Reputation: 323

The key in the JSON Object contains a space, so you can't use the dot-operator shortcut to index into the object. You should be able to use the traditional index approach:

<td>{{data['eloisa moreira']}}</td>

Upvotes: 2

Related Questions