Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

angularjs - Order by Object key in ng-repeat

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...