简体   繁体   English

如何使用嵌套属性在AngularJS中排序

[英]How to orderby in AngularJS using Nested property

This is the json that is generated using PHP 这是使用PHP生成的json

[{"Sale":{"id":"1","customer_id":"1","amount":"15","created":"2014-05-17"}}]

Doing orderBy:id is obviously not working. orderBy:id显然不起作用。 I read in other posts that an orderBy function needs to be created for this kind of data structure. 我在其他帖子中读到需要为这种数据结构创建orderBy函数。 I am not able to create the function. 我无法创建该功能。 Can anyone please tell me what is the correct way to approach this? 任何人都可以告诉我这是正确的方法吗?

Suppose you have: 假设你有:

$scope.sales = [{"Sale":{"id":"1"}},{"Sale":{"id":"2"}},{"Sale":{"id":"3"}}];

Why not just do following: 为什么不这样做:

<div ng-repeat="sale in sales | orderBy:'Sale.id':true">
    {{ sale.Sale.id }}
</div>

It works well with my case. 它适用于我的情况。 May be Angular did not support it at the time you asked the question. 可能是Angular在你问这个问题的时候不支持它。

These type of data manipulations I like to keep them in the proper angular objects and for that reason I would create my custom filter, something like: 这些类型的数据操作我喜欢将它们保存在适当的角度对象中,因此我会创建自定义过滤器,例如:

var sampleSource=  [{"Sale":{"id":"8","customer_id":"1","amount":"15","created":"2014-05-17"}}, {"Sale":{"id":"5","customer_id":"6","amount":"15","created":"2015-05-17"}}];

var myApp = angular.module('myApp',[]);

myApp.filter('myFilter', function() {
 return function(items) {  
    items.sort(function(a,b){   
        if (parseInt(a.Sale.id) > parseInt(b.Sale.id))
            return 1;
        if (parseInt(a.Sale.id) < parseInt(b.Sale.id))
            return -1;         
        return 0; })
});

Important: I recommend the custom filter because as personal preference I do not like to overload my controllers or other objects with tasks(code) that I can separate on other objects which gives me more independence and cleaner code(one of the things I love about angular) but besides this personal preference I would say that this is not the only way but if you share my reasons behind it I hope it helps. 重要提示:我推荐使用自定义过滤器,因为根据个人喜好,我不喜欢使用我可以在其他对象上分离的任务(代码)来重载我的控制器或其他对象,从而为我提供更多独立性和更清晰的代码(我喜欢的事情之一)角度)但除了这个个人偏好,我会说这不是唯一的方法,但如果你分享我背后的原因,我希望它有所帮助。

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

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