如何按键排序为整数?

我有以下对象;

 $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">

当前输出顺序为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 AND代码段

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>

注意:
上面的过滤器需要Underscore.js,如果不使用它,可以重写过滤器。

09-25 21:29