ng-repeat directive sort the data when using (key, value)

前端 未结 7 2110
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 09:40

I have a code something like this with ng-repeat = \"(key,value) in data\". In Controller:

  $scope.Dates = {\"Today\":\"30\",
                  \"This Wee         


        
相关标签:
7条回答
  • 2020-12-08 10:03

    EDIT: I've filed a bug, feel free to +1

    ECMAScript does not specify order in which keys should be iterated, however all major browsers implement objects as linked hash map (preserves order) and a lot of js libraries depend on this behavior and so we've got used to it and it's hardly going to change.

    Angular on the other hand (which is totally unexpected) sort it alphabetically. I've inspected the source code myself, it is hard-coded there and it would be nice if it got resolved one day. Otherwise the (k, v) in obj feature is completely useless.

    You really cant do anything with that, tricking angular to think your result is an array is not useful for anything, because you would need numeric keys then...

    If this is okay, you can define getter for length:

    Object.defineProperty(yourResultObjectOrPrototype, 'length', {
      get: function(){
        return Object.keys(this).length;
      }
    })
    

    Otherwise you'll need some kind of filter which will iterate object using for(var k in obj) and store result in array.

    0 讨论(0)
提交回复
热议问题