angularjs ngRepeat orderBy当属性键有空格时

时间:2014-04-17 13:41:10

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

我以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>

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

我错过了什么?

谢谢!

2 个答案:

答案 0 :(得分:11)

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

<强> HTML

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

<强> JS

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

答案 1 :(得分:8)

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

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