我有一个名为 $scope.segments
的对象数组,如下所示:
[
{
"_id": "55d1167655745c8d3679cdb5",
"job_id": "55d0a6feab0332116d74b253",
"status": "available",
"sequence": 1,
"body_original": "Such a fork",
"__v": 0,
"body_translated": "Tal bifurcación"
},
{
"_id": "55d1167655745c8d3679cdb4",
"job_id": "55d0a6feab0332116d74b253",
"status": "available",
"sequence": 0,
"body_original": "So this is it.",
"__v": 0,
"body_translated": "Así que esto es."
}
]
我需要按顺序排列数组。因此,我需要先出现序列 0,然后出现序列 1,依此类推。在一个 View 中,我正在这样做并且它有效:
<ul ng-repeat="segment in segments | orderBy: 'sequence'">
<li>{{ segment.sequence }}</li>
</u>
但是,我需要 orderBy 过滤器才能在 Controller 中工作。我这样做:
$scope.test = $filter('orderBy')($scope.segments, 'sequence');
其中,$scope.test 应该是我基于序列属性排序的对象数组。但是,当我执行 console.log('$scope.test') 时,会显示一个空数组 ([]
)。我想 $filter 在 Controller 中不起作用。
关于如何解决这个问题的任何想法?谢谢!
最佳答案
我猜你只是没有在 Controller 中正确注入(inject) $filter
服务,因为这对我有用。
<body ng-controller="MainCtrl">
<ul ng-repeat="segment in segments | orderBy: 'sequence'">
<li>{{segment.sequence}}</li>
</ul>
<script src="vendors/angular.min.js"></script>
<script>
angular.module('app', [])
.controller('MainCtrl', ['$scope', '$filter', function($scope, $filter) {
$scope.segments = [
{
"_id": "55d1167655745c8d3679cdb5",
"job_id": "55d0a6feab0332116d74b253",
"status": "available",
"sequence": 1,
"body_original": "Such a fork",
"__v": 0,
"body_translated": "Tal bifurcación"
},
{
"_id": "55d1167655745c8d3679cdb4",
"job_id": "55d0a6feab0332116d74b253",
"status": "available",
"sequence": 0,
"body_original": "So this is it.",
"__v": 0,
"body_translated": "Así que esto es."
}
];
$scope.test = $filter('orderBy')($scope.segments, 'sequence');
console.log($scope.test);
}]);
</script>
</body>
关于javascript - 使用 $filter 根据 Angular Controller 中的属性对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32099716/