I have an array of objects called $scope.segments
like this:
[
{
"_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."
}
]
I need to order this by array by sequence. So, I need the sequence 0 to appear first, the sequence 1 to appear next, and so on. In a view, I'm doing this and it works:
<ul ng-repeat="segment in segments | orderBy: 'sequence'">
<li>{{ segment.sequence }}</li>
</u>
However, I need the orderBy filter to work in a controller. I'm doing this:
$scope.test = $filter('orderBy')($scope.segments, 'sequence');
Where, $scope.test should be my ordered array of objects based on the the sequence property. However, when I do console.log('$scope.test') an empty array ([]
) shows. I imagine the $filter is not working in the controller.
Any ideas on how to solve this? Thanks!
I guess you just didn't inject the $filter
service in your controller properly, because this worked for me.
<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>
You can always just sort the array (then you can even omit the orderBy
in the view - although you lose some of the magic with the bindings if anything is added):
$scope.segments.sort(function(a, b) {
return a.sequence - b.sequence;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With