OrderBy过滤器角度与嵌套对象抛出错误

时间:2016-06-15 10:11:23

标签: angularjs

我有一个这样的数组:

[{
    "type": "adserver",
    "stats": {
        "10021": 48082,
        "10023": 1741
    }
}, {
    "type": "adserver",
    "stats": {
        "10021": 12312,
        "10023": 23
    }
}, {
    "type": "adserver",
    "stats": {
        "10021": 53423,
        "10023": 54
    }
}, {
    "type": "adserver",
    "stats": {
        "10021": 12345,
        "10023": 12
    }
}]

我正在尝试使用:

ng-repeat = "array | orderBy:'stats.10021'"

并抛出此错误:

  

语法错误:令牌'.10021'是第6列的意外令牌   表达式[stats.10021]从[.10021]开始。

3 个答案:

答案 0 :(得分:1)

该错误与您尝试访问哪些键是数字的对象属性有关。您必须使用方形参数访问属性。

您无法使用点表示法访问对象属性,哪些键是数字!

请改为尝试:

ng-repeat = "(key, value) in array | orderBy:'stats['10021']"

答案 1 :(得分:0)

Javascript对象属性名称不能以数字开头,因此您只能使用[]表示法将其作为字符串名称访问

尝试

orderBy:stats['10021']

答案 2 :(得分:0)

jsfiddle

<div ng-app="myApp" ng-controller="Ctrl">
  <div ng-repeat="single in array | orderBy:'stats.10021'">
     <businesscard>{{single.type}} {{single.stats}}</businesscard>
  </div>
</div>

angular.module('myApp', [])
.controller('Ctrl', function($scope) {
    $scope.array = [{"type":"adserver","stats":{"10021":48082,"10023":1741}}, {"type":"adserver","stats":{"10021":12312,"10023":23}}, {"type":"adserver","stats":{"10021":53423,"10023":54}}, {"type":"adserver","stats":{"10021":12345,"10023":12}}]
});
  

输出

adserver {&#34; 10021&#34;:12312,&#34; 10023&#34;:23}

adserver {&#34; 10021&#34;:12345,&#34; 10023&#34;:12}

adserver {&#34; 10021&#34;:48082,&#34; 10023&#34;:1741}

adserver {&#34; 10021&#34;:53423,&#34; 10023&#34;:54}