如何使用带有键|值对的ng repeat进行排序
How to sort using ng-repeat with a key|value pair
我正试图按最后一条消息的顺序列出我的应用程序的一些消息传递线程(这样较新的消息就在顶部),但我在使用Angular附带的orderBy
过滤器时遇到了一些问题。
下面是一个我们正在排序的对象的示例。
$scope.messageThreads = {
'102842': {
name: 'John Doe',
avatar: 'http://directlink/img.png',
last_message: 5,
messages: [
{ content: 'Hello!', from: '102842', to: '312124', date: 5 }
]
},
'59251275': {
name: 'Thomas Doe',
avatar: 'http://directlink/img.png',
last_message: 28,
messages: [
{ content: 'Hey jack', from: '59251275', to: '1231251', date: 12 },
{ content: 'Hey Thomas', from: '1231251', to: '59251275', date: 28 }
]
}
}
存储在一个名为messageThreads
的简单对象中。
在HTML文档中,我们在Key/Value对中循环这些,如下所示:
<div ng-repeat="(id, thread) in messageThreads | orderBy: '-thread.last_message'">
Thread ID: {{id}} - Last message: {{thread.last_message}}
</div>
不幸的是,它根本没有对消息进行排序。显示的输出为:
Thread ID: 102842 - Last message: 5
Thread ID: 59251275 - Last message: 28
然而,它应该是:
Thread ID: 59251275 - Last message: 28
Thread ID: 102842 - Last message: 5
将-thread.last_message
更改为thread.last_message
并不能解决此问题。
这里有一个解决方案,但有一个问题是它将items对象转换为数组,您将无法再访问"关联数组"的键,就像您在items片段中使用(key,item)一样
app.filter('orderObjectBy', function() {
return function(items, field, reverse) {
var filtered = [];
angular.forEach(items, function(item,key) {
**item.key = key;** //Here you can push your key to get in returned Object
filtered.push(item);
});
filtered.sort(function (a, b) {
return (a[field] > b[field] ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
});
在HTML:中
<div ng-repeat="(id, thread) in messageThreads | orderObjectBy:'last_message':true">
Thread ID: {{thread.key}} - Last message: {{thread.last_message}}
</div>
相关文章:
- ng init中的表达式无法使用ng repeat
- Angular ng repeat order将多个字段作为一个字段
- 访问ng repeat中的第一个项目
- Angular js+ng repeat+字母数字索引不起作用
- 如何正确应用Angularjs ng repeat
- AngularJS Navigation (li ng-repeat, create header li), DOM
- 如何使用ng repeat中的选定输入更新我的对象
- 无法使用ng repeat检索动态创建的JSON对象的属性
- 使用 ng-repeat访问 ng 表单元素/值
- Toggle Switch在包含ng model和ng repeat之后不进行切换
- 如何在ng repeat angular js中使用$index
- 在Angularjs中,我如何使用ng repeat、ng model和ng click来动态更改内容
- ng repeat在ng repeat-过滤器不工作
- 在ng repeat中使用带有orderBy的方法
- Angular JS ng-repeat
- 在ng repeat中使ng disabled为true
- AngularJS:如何在ng repeat中使用$index
- 复选框无法正常使用ng repeat,AngularJs
- 如何避免在HTML中使用ng repeat对url名称进行硬编码
- 替换ng repeat中的一些符号