如何使用嵌套属性在 AngularJS 中排序 [英] How to orderby in AngularJS using Nested property

查看:26
本文介绍了如何使用嵌套属性在 AngularJS 中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是使用PHP生成的json

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

orderBy:id 显然是行不通的.我在其他帖子中读到需要为这种数据结构创建一个 orderBy 函数.我无法创建该函数.谁能告诉我解决这个问题的正确方法是什么?

解决方案

我喜欢将这些类型的数据操作保留在适当的角度对象中,因此我会创建自定义过滤器,例如:

var sampleSource= [{"Sale":{"id":"8","customer_id":"1","amount":"15","created":"2014-05-17"}}, {"销售":{"id":"5","customer_id":"6","amount":"15","created":"2015-05-17"}}];var myApp = angular.module('myApp',[]);myApp.filter('myFilter', function() {返回函数(项目){items.sort(function(a,b){如果 (parseInt(a.Sale.id) > parseInt(b.Sale.id))返回 1;如果 (parseInt(a.Sale.id) < parseInt(b.Sale.id))返回-1;返回0;})});

<块引用>

重要提示:我推荐自定义过滤器,因为作为个人偏好,我不喜欢用我可以在其他对象上分离的任务(代码)使控制器或其他对象过载,这使我更加独立和更简洁的代码(我喜欢 angular 的其中一件事)但除了这种个人偏好之外,我想说这不是唯一的方法,但如果你分享我背后的原因,我希望它有所帮助.

This is the json that is generated using PHP

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

Doing orderBy:id is obviously not working. I read in other posts that an orderBy function needs to be created for this kind of data structure. I am not able to create the function. Can anyone please tell me what is the correct way to approach this?

解决方案

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.

这篇关于如何使用嵌套属性在 AngularJS 中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆