【发布时间】: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