使用AngularJs中的ng-repeat对对象排序

时间:2015-02-06 05:17:49

标签: javascript angularjs sorting

我的问题是: 我想使用ng-repeat对其子元素为Object的Object进行排序。

facets = {
    'tm_mailbox': {buckets: [{key:'budlion', doc_count:1037}]},
       'tm_user': {buckets: [{key:'karl', doc_count:10}, {key:'kael2', doc_count:111}] },
    'tm_message': {buckets: [{key:'sylvia', doc_count:298}] }};

facets_ordered_keys = ['tm_user', 'tm_message', 'tm_mailbox']

默认情况下,对象将按A-Z排序。我想订购这个物品。

我使用了两个 ng-repeat ,第一个循环将读取已排序的键,第二个循环将按键读取值,例如伪代码中的循环:

for k in facets_ordered_keys:
    print k
    for v in facets[k]:
       print v

但我无法在第二次重复播放中阅读方面[k]。

以下是角js中的代码:



<!doctype html>
<html ng-app>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>

  <div ng-init="facets =
    {'tm_mailbox': {buckets: [{key:'budlion', doc_count:1037}]},
    'tm_user': {buckets: [{key:'karl', doc_count:10}, {key:'kael2', doc_count:111}] },
    'tm_message': {buckets: [{key:'sylvia', doc_count:298}] }};
    facets_ordered_keys = ['tm_user', 'tm_message', 'tm_mailbox']
">
    <div ng-repeat=" k in facets_ordered_keys ">
      <p>k is: {{k}}</p>
      <p>In facets values is:{{facets[k]}}</p>
    </div>
    <hr>
   
   <!-- why i cannot read facets[k]? -->  
    <div ng-repeat=" k in facets_ordered_keys ">
      <dt>{{k}}</dt>
      <dl ng-repeat="v in facets[k]">
        <dd ng-repeat="bucket in v.buckets">
          <label>{{bucket.key}}</label>
          <span>{{bucket.doc_count}}</span>
        </dd>
      </dl>
    </div>
    
  </div>

</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

试试这个。

<!doctype html>
<html ng-app>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>

  <div ng-init="facets =
    {'tm_mailbox': {buckets: [{key:'budlion', doc_count:1037}]},
    'tm_user': {buckets: [{key:'karl', doc_count:10}, {key:'kael2', doc_count:111}] },
    'tm_message': {buckets: [{key:'sylvia', doc_count:298}] }};
    facets_ordered_keys = ['tm_user', 'tm_message', 'tm_mailbox']
">
    <div ng-repeat=" k in facets_ordered_keys ">
      <p>k is: {{k}}</p>
      <p>In facets values is:{{facets[k]}}</p>
    </div>
    <hr>
   
   <!-- why i cannot read facets[k]? -->  
    <div ng-repeat=" k in facets_ordered_keys ">
      <dt>{{k}}</dt>
      <dl ng-repeat="v in facets[k]">  
        <dd ng-repeat="bucket in v">		
          <label>{{bucket.key}}</label>
          <span>{{bucket.doc_count}}</span>
        </dd>
      </dl>
    </div>
    
  </div>

</body>

</html>