如何在使用 ng-repeat 循环遍历同一个 json 时按 json 的一个属性排序?



>

<div class="question" ng-repeat="x in asdf">
        <p >{{x}}</p>
</div>

json: -

  $scope.asdf = {
  "1": {"question":"Jquery, hide radio button label if not selected","votes": "233", "answers": "2", "views": "2", "tags": "html", "dateString": "Aug 22 2016 16:52", "date": "1471864975000"},
  "2": {"question":"Jquery, hide radio button label if not selected","votes": "233", "answers": "2", "views": "2", "tags": "html", "dateString": "Aug 22 2016 16:52", "date": "1471864975000"},
  "3": {"question":"Jquery, hide radio button label if not selected","votes": "233", "answers": "2", "views": "2", "tags": "html", "dateString": "Aug 22 2016 16:52", "date": "1471864975000"},
  "5": {"question":"Jquery, hide radio button label if not selected","votes": "233", "answers": "2", "views": "2", "tags": "html", "dateString": "Aug 22 2016 16:52", "date": "1471864975000"},
  "6": {"question":"Jquery, hide radio button label if not selected","votes": "233", "answers": "2", "views": "2", "tags": "html", "dateString": "Aug 22 2016 16:52", "date": "1471864975000"},
  "7": {"question":"Jquery, hide radio button label if not selected","votes": "233", "answers": "2", "views": "2", "tags": "html", "dateString": "Aug 22 2016 16:52", "date": "1471864975000"},
  "8": {"question":"Jquery, hide radio button label if not selected","votes": "233", "answers": "2", "views": "2", "tags": "html", "dateString": "Aug 22 2016 16:52", "date": "1471864975000"},
  "9": {"question":"Jquery, hide radio button label if not selected","votes": "233", "answers": "2", "views": "2", "tags": "html", "dateString": "Aug 22 2016 16:52", "date": "1471864975000"}
};

这就是我要做的,按日期排序(日期是json中的一个属性)

<div class="question" ng-repeat="x in asdf | orderBy : date">
    <p >{{x}}</p>
</div>

也试过

<div class="question" ng-repeat="x in asdf | orderBy : x.date">
<div class="question" ng-repeat="x in asdf | orderBy : asdf.date">

似乎什么都不起作用

1 -为什么不可能?

2 -我该怎么做才能达到类似的效果?

注意-我想用class="question"在特定的div上重复,不想创建另一个div。

在本例中,orderBy过滤器参数需要是字符串。所以这应该可以工作:

<div class="question" ng-repeat="x in asdf | orderBy : 'date'">
    <p>{{x}}</p>
</div>

以下是来自文档的解释:

string:一个Angular表达式。这个表达式将被求值针对每个项目和结果将用于排序。为例如,使用'label'按一个名为label或的属性进行排序的标签。子字符串(0,3)'按标签的前3个字符排序财产。(常量表达式的结果被解释为属性名用于比较。例如,使用"special"命名"'"(注意额外的一对引号),以便根据属性进行排序特殊的名字。)

从https://docs.angularjs.org/api/ng/filter/orderBy

编辑:但是orderBy过滤器只适用于数组(或类似数组的对象)

集合可以是Array或类数组对象(如NodeList、jQuery对象,typearray, String等)。

因此,首先需要将数据放入不同的结构中,或者使用自定义解决方案对其进行排序。如:

Angular order对象可能吗?

最新更新