简体   繁体   English

AngularJS,Ng-repeat改变/改变Json数组的顺序

[英]AngularJS, Ng-repeat changes / alters the order of a Json array

Dear friends of SO: 亲爱的朋友们:

18 of March, 2014. I'm dealing with a situation here, at the moment of using ng-repeat, the elements inside the array (which I'm fetching from a Json string) change the original order. 2014年3月18日。我正在处理这里的情况,在使用ng-repeat时,数组中的元素(我从Json字符串中获取)会改变原始顺序。

Just to be clear, the first variables inside the array are related to the order_id and the person name, while the last ones, are related to the credit information. 需要明确的是,数组中的第一个变量与order_id和人名相关,而最后一个变量与信用信息相关。

I'm getting a completely messed up order on the information, could be alphabetical, I'm not sure. 我在信息上得到一个完全混乱的订单,可能是字母,我不确定。

No weird things in the code: 代码中没有奇怪的东西:

<li ng-repeat="(variable, valor) in records" >
     <a href="">{{variable}}: </a>
     <a href="">{{valor}}</a>
</li>

Any reference? 任何参考?

Thanks in advance! 提前致谢! Chris; 克里斯;

chris: the sorting of the keys was alphabetical, and this was fixed in the recent release of Angular 1.4. 克里斯:键的排序是按字母顺序排列的,这是在最近发布的Angular 1.4中修复的。 As stated in the official Angular documentation below: 如下面的官方Angular文档中所述:

Version 1.4 removed the alphabetic sorting. 版本1.4删除了字母排序。 We now rely on the order returned by the browser when running for key in myObj 我们现在依赖于for key in myObj运行for key in myObj时浏览器返回的顺序

https://docs.angularjs.org/api/ng/directive/ngRepeat https://docs.angularjs.org/api/ng/directive/ngRepeat

You could use the orderBy filter to do this. 您可以使用orderBy过滤器来执行此操作。 I am giving an example below; 我在下面给出一个例子;

Suppose yo have a controller like this: 假设你有一个像这样的控制器:

function Ctrl($scope) {
  $scope.friends =
      [{name:'John', phone:'555-1212', age:19},
       {name:'Mary', phone:'555-9876', age:10},
       {name:'Mike', phone:'555-4321', age:21},
       {name:'Adam', phone:'555-5678', age:35},
       {name:'Julie', phone:'555-8765', age:29}]
  $scope.predicate = '-age';
}

And in HTML: 在HTML中:

  <div ng-controller="Ctrl">
    <table class="friend">
      <tr>
        <th>Name

        <th>Phone Number</th>
        <th>Age</th>
      </tr>
      <tr ng-repeat="friend in friends | orderBy:predicate">
        <td>{{friend.name}}</td>
        <td>{{friend.phone}}</td>
        <td>{{friend.age}}</td>
      </tr>
    </table>
  </div>

The result would be like: 结果如下:

Name    Phone Number    Age
Adam    555-5678        35
Julie   555-8765        29
Mike    555-4321        21
John    555-1212        19
Mary    555-9876        10

I think something like this will solve your issue. 我认为这样的事情可以解决你的问题。

If you want to sort ascending according to age just change this line in your controller 如果要根据年龄对升序进行排序,只需在控制器中更改此行即可

$scope.predicate = '+age';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM