【问题标题】:ng-repeat gets wrong $index when sortingng-repeat 在排序时得到错误的 $index
【发布时间】:2014-07-03 00:09:05
【问题描述】:

我有一个简单的对象:

"socials": {
  "f": "#/facebook/",
  "B": "#/behance/",
  "d": "#/dribble/",
  "L": "#/linkedin/",
  "P": "#/pinterest/"
}

当我尝试使用 ng-repeat="(key, value) in data.socials" 时,它的排序如下:B L P d f.

$index 捕获错误的索引,就像它已经被排序一样。如何正确订购它,因为它在 JSON 文件中?或者也许我怎样才能获得正确的索引来使用orderBy: correctIndex?我发现了一个小提琴,它显示了一个完全像这样的问题:http://jsfiddle.net/zMjVp/

【问题讨论】:

标签: angularjs ng-repeat


【解决方案1】:

ngRepeat 按字母顺序迭代对象键以按 $index (see the code for ngRepeat on Github) 管理跟踪项。

要控制ngRepeat 中的迭代顺序,您应该将对象结构转换为保证迭代顺序的数组:

JavaScript:

var jsonData = {
    "socials": {
        "f": "#/facebook/",
        "B": "#/behance/",
        "d": "#/dribble/",
        "L": "#/linkedin/",
        "P": "#/pinterest/"
    }
};

var socialsList = [];
angular.forEach(jsonData.socials, function(value, key){
    socialsList.push({
        key: key,
        value: value
    });
});
$scope.socialsList = socialsList;

HTML:

然后更新您的 HTML 以迭代列表而不是对象。

<div ng-repeat="item in socialsList">
    <p> {{item.key}} : {{item.value}} </p> 
</div>

注意:

除非您使用delete 运算符,否则您通常可以依赖for...in 循环的顺序。这不是保证,但它通常是可靠的。 See the MDN documentation on for...in loops

【讨论】:

  • 我认为您在推送时指的是 socialsList 变量
猜你喜欢
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多