【问题标题】:angularjs ngRepeat orderBy when property key has spaces当属性键有空格时,angularjs ngRepeat orderBy
【发布时间】:2014-06-01 19:42:30
【问题描述】:

我得到了一些 JSON 格式的数据,其中一些键中有空格:

[
    {
        "PlainKey": "SomeValue",
        "Spaced Key": "SomeValue"
    },
    {
        "PlainKey": "SomeValue2",
        "Spaced Key": "SomeValue2"
    }
]

这发生在某个时候:

$http.get('https://dl.dropboxusercontent.com/u/80497/htmlTesting/properties/credits.properties' + '?callback=JSON_CALLBACK').then(function (data) {
            $scope.credits = data.data;
        }, function (error) {
            $scope.errorOccured = true;
            console.log("Error:");
            console.log(error);
        });

然后用ng-repeat来显示,有顺序:

<select ng-model="corder">
  <option value="PlainKey">Plain Key</option>
  <option value="Spaced Key">Spaced Key</option>
</select>

<li ng-repeat="credit in credits | orderBy:corder" >
.....
</li>

这不起作用(我得到一个例外) (PlainKey 有效,因为没有空格)。

我也尝试将值放入'

<select ng-model="corder">
  <option value="'PlainKey'">Plain Key</option>
  <option value="'Spaced Key'">Spaced Key</option>
</select>

这似乎改变了顺序,但不正确。

我错过了什么?

谢谢!

【问题讨论】:

  • 用单引号将Spaced Key 括起来会导致orderBy 查找键为'Spaced Key' 的对象属性,引号包含在实际属性名称中。因此,它期望像$scope.credits[0]["'Spaced Key'"] 这样的东西可以访问。由于这不可用,这就是您看到不一致行为的原因。
  • @miqid 好的,谢谢。那么在这种情况下,您将如何通过Spaced Key 订购?
  • 您可以改为为orderBy 提供谓词排序函数(而不是作为排序依据的属性名称)。这是一个Plunker 来说明我的意思。
  • @miqid 把它作为答案,我会接受它。

标签: angularjs angularjs-ng-repeat angularjs-orderby


【解决方案1】:

评论似乎有帮助,所以我将其作为答案:

对对象属性名称中带有空格的项目进行排序的一种方法是将谓词排序函数传递给orderBy,而不是指定对象属性名称。具体相关修改:

HTML:

<li ng-repeat="credit in credits | orderBy:predicate">

JS:

$scope.predicate = function(val) {
  // $scope.corder corresponds to the object property name to sort by
  return val[$scope.corder];
}

演示Plunker

【讨论】:

  • 每当我使用这样的谓词作为过滤器而不是控制器中的函数时,我得到的结果几乎看起来是随机排序的。每次使用时,顺序都会随机播放。
【解决方案2】:

最简单的方法,就是用UTF8编码把一个字段名括起来做引号:

HTML

<li ng-repeat="item in items | orderBy:'\u0022Spaced Key\u0022'">

JS

$scope.orderKey = '\u0022Spaced Key\u0022';

【讨论】:

  • 不错!这是最好的答案,我想。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-13
相关资源
最近更新 更多