How to repeat “key” in ngRepeat one time only (Ang

2019-09-11 02:33发布

The problem is leaving in the JSON Array response from the Backend/DB. I'm getting the response of the database in the correct json format:

[
  0: {
       "Grade": 100,
       "AB001": 1,
       "AB002": 0,
       "AB003": 9,
       "AB004": 5
     },
  1: {
       "Grade": 98,
       "AB001": 3,
       "AB002": 0,
       "AB003": 0,
       "AB004": 0
     }
...
] (10 objects as result)

Thus displayed in the Firebug console, when you click the Response of the GET Request. To retrieve the keys who are represented in double quotes I've used the ngRepeat directive in my view like following:

<thead>
  <tr ng-repeat="d in data">
      <th ng-repeat="(key, value) in d">
          {{key}}
      </th>
  </tr>
</thead>
...

Only the problem is, that the key gets repeated 10 times. But I want to repeat the keys one time that means for example the key Grade is only one time in a th-tag and so on..

How can I implement this? I've tried it with angular's forEach() but it wasn't a solution.

3条回答
时光不老,我们不散
2楼-- · 2019-09-11 02:40

You could use the unique filter from AngularUI (source code available here: AngularUI unique filter) and use it directly in the ng-options (or ng-repeat).

Try This:

<thead>
  <tr ng-repeat="d in data">
      <th ng-repeat="(key, value) in d | unique:'key'">
          {{key}}
      </th>
  </tr>
</thead>
查看更多
Fickle 薄情
3楼-- · 2019-09-11 02:45

this answer may be help you

<thead>
<tr ng-repeat="d in data">
   <th ng-if="$parent.$index == 0" ng-repeat="(key, value) in d">
       {{key}}
   </th>
</tr>

查看更多
Emotional °昔
4楼-- · 2019-09-11 02:47

If you have the exact same keys in each object in the array, you could achieve this with:

<thead>
  <tr>
    <th ng-repeat="(key, value) in data[0]">
        {{key}}
    </th>
  </tr>
</thead>

In your snippet you are doing a double loop, listing each key, for each element in the array.

查看更多
登录 后发表回答