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

懵懂的女人 提交于 2020-01-17 04:55:06

问题


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.


回答1:


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.




回答2:


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>



回答3:


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>



来源:https://stackoverflow.com/questions/32716999/how-to-repeat-key-in-ngrepeat-one-time-only-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!