7

我得到一些 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>

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

我错过了什么?

谢谢!

4

2 回答 2

11

最简单的方法,只需用 UTF8 代码将字段名称括起来作为引号:

HTML

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

JS

$scope.orderKey = '\u0022Spaced Key\u0022';
于 2015-06-02T14:20:39.557 回答
9

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

对对象属性名称中带有空格的项目进行排序的一种方法是将谓词排序函数传递给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

于 2014-04-22T06:08:49.067 回答