angularjs ngRepeat orderBy当属性键有空格时

Ben*_*Ben 7 angularjs angularjs-ng-repeat angularjs-orderby

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

[
    {
        "PlainKey": "SomeValue",
        "Spaced Key": "SomeValue"
    },
    {
        "PlainKey": "SomeValue2",
        "Spaced Key": "SomeValue2"
    }
]
Run Code Online (Sandbox Code Playgroud)

这发生在某个时刻:

$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);
        });
Run Code Online (Sandbox Code Playgroud)

然后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>
Run Code Online (Sandbox Code Playgroud)

这不起作用(我得到一个例外)(PlainKey因为没有空格,所以工作).

我也尝试将值放入':

<select ng-model="corder">
  <option value="'PlainKey'">Plain Key</option>
  <option value="'Spaced Key'">Spaced Key</option>
</select>
Run Code Online (Sandbox Code Playgroud)

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

我错过了什么?

谢谢!

Ale*_*lex 11

最简单的方法是,用引号标记的UTF8代码包围一个字段名称:

HTML

<li ng-repeat="item in items | orderBy:'\u0022Spaced Key\u0022'">
Run Code Online (Sandbox Code Playgroud)

JS

$scope.orderKey = '\u0022Spaced Key\u0022';
Run Code Online (Sandbox Code Playgroud)

  • 太好了!这是最好的答案. (3认同)

miq*_*iqh 8

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

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

HTML:

<li ng-repeat="credit in credits | orderBy:predicate">
Run Code Online (Sandbox Code Playgroud)

JS:

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

示范Plunker.