在 ng-repeat 中按对象键排序 [英] Order by Object key in ng-repeat
本文介绍了在 ng-repeat 中按对象键排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何按键按整数排序?
我有以下对象;
$scope.data = {0":{数据:零"},1":{数据:一个"},2":{数据:两个"},3":{数据:树"},5":{数据:五"},6":{数据:六"},10":{数据:十"},11":{数据:十一"},12":{数据:十二"},13":{数据:十三"},20":{数据:二十"}}
HTML:
当前输出顺序为1,10,11,12,13,14,2,20,3,4,5,6
但我想要1,2,3,4,5,6,10,11,12,13,14,20
<代码>|orderBy:key
不要为我工作.
有什么想法吗?
谢谢!
解决方案 一个选项是使用中间过滤器.
PLUNK 和代码片段
var app = angular.module('app', []);app.controller('MainCtrl', function($scope) {$scope.template = {0":{数据:零"},1":{数据:一个"},2":{数据:两个"},3":{数据:树"},5":{数据:五"},6":{数据:六"},10":{数据:十"},11":{数据:十一"},12":{数据:十二"},13":{数据:十三"},20":{数据:二十"}}});app.filter('toArray', function() { return function(obj) {if (!(obj instanceof Object)) 返回 obj;返回 _.map(obj, function(val, key) {return Object.defineProperty(val, '$key', {__proto__: null, value: key});});}});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script><body ng-app="app" ng-controller="MainCtrl"><div ng-repeat="(key, value) in template| toArray | orderBy:key">{{key}} : {{value.$key}} : {{value.data}}</div>
注意:
以上过滤器需要Underscore.js,如果不使用,可以重写过滤器.
How can I order by key as integer?
I have the following Object;
$scope.data = {
"0": { data: "ZERO" },
"1": { data: "ONE" },
"2": { data: "TWO" },
"3": { data: "TREE" },
"5": { data: "FIVE" },
"6": { data: "SIX" },
"10":{ data: "TEN" },
"11": { data: "ELEVEN" },
"12": { data: "TWELVE" },
"13": { data: "THIRTEEN" },
"20": { data: "TWENTY"}
}
HTML:
<div ng-repeat="(key,value) in data">
The current output order is 1,10,11,12,13,14,2,20,3,4,5,6
But I want 1,2,3,4,5,6,10,11,12,13,14,20
| orderBy:key
don't work for me.
Any ideas?
Thanks!
解决方案 An option would be use an intermediate filter.
PLUNK AND Code Snippet
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.template = {
"0": { data: "ZERO" },
"1": { data: "ONE" },
"2": { data: "TWO" },
"3": { data: "TREE" },
"5": { data: "FIVE" },
"6": { data: "SIX" },
"10":{ data: "TEN" },
"11": { data: "ELEVEN" },
"12": { data: "TWELVE" },
"13": { data: "THIRTEEN" },
"20": { data: "TWENTY"}
}
});
app.filter('toArray', function() { return function(obj) {
if (!(obj instanceof Object)) return obj;
return _.map(obj, function(val, key) {
return Object.defineProperty(val, '$key', {__proto__: null, value: key});
});
}});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>
<body ng-app="app" ng-controller="MainCtrl">
<div ng-repeat="(key, value) in template| toArray | orderBy:key">{{key}} : {{value.$key}} : {{value.data}}</div>
<body>
NOTE:
The above filter requires Underscore.js, if you don't use it, can rewrite the filter.
这篇关于在 ng-repeat 中按对象键排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文