将Object的数组转换为Angular中的HTML表

时间:2017-01-04 13:55:44

标签: javascript html angularjs angularjs-ng-repeat

我有一个像这样的对象列表:

var entryList = [
  {
    "Key1": "Value1",
    "Key2": "Value2",
    "Key3": "Value3"
  },
  {
    "Key1": "Value1",
    "Key2": "Value2",
    "Key3": "Value3"
  },
  {
    "Key1": "Value1",
    "Key2": "Value2",
    "Key3": "Value3"
  }
]

我想创建一个像这样的HTML标签:

+--------+--------+--------+
|  Key1  |  Key2  |  Key3  |
+--------+--------+--------+
| Value1 | Value2 | Value3 |
| Value4 | Value5 | Value6 |
| Value7 | Value8 | Value9 |
+--------+--------+--------+

当我们点击标题

时,按键对值进行排序

3/4的代码在html

<table class="table table-bordered table-striped">

<thead>
        <tr>
            <td ng-repeat="(key, value) in $ctrl.entryList[0]">
                <a ng-click="$ctrl.sortType = key; $ctrl.sortReverse = !$ctrl.sortReverse">
                    {{key}}
                    <span ng-show="$ctrl.sortType == key && !$ctrl.sortReverse" class="fa fa-caret-down"></span>
                    <span ng-show="$ctrl.sortType == key && $ctrl.sortReverse" class="fa fa-caret-up"></span>
                </a>
            </td>
        </tr>
    </thead>

    <tbody>
        <tr ng-repeat="itemFormData in $ctrl.entryList | orderBy:sortType:sortReverse | filter:searchForm">
            <td ng-repeat="(key, value) in itemFormData">{{ itemFormData[key] }}</td>
        </tr>
    </tbody>

</table>

表格显示正确,但是当我点击标题对列进行排序时,没有任何反应。如果您有一些建议并感谢您的时间。

1 个答案:

答案 0 :(得分:0)

不要将代码直接放在ng-click中,而是在控制器中创建一个函数。这就是控制器的用途!

<a ng-click="selectSortType(key)">

$scope.selectSortType = function(key) {
  $scope.sortType = key; 
  $scope.sortReverse = !$scope.sortReverse;
};

https://jsfiddle.net/cfhzub2y/1/