Angularjs: $filter in controller

All we need is an easy explanation of the problem, so here it is.

Having issues with getting this filter to work.

$scope.imgCollection.then(function (images) {
    $scope.images = images.thisGal_images;

    if ($scope.images[0].order == '0') {
        $scope.images = $filter('orderBy')($scope.images, 'orgName');
    } else {
        console.log('sort order');
        $scope.images = $filter('orderBy')($scope.images, 'sortOrder');

$scope.images returns a list of images from the database. On the initial upload, the sortOrder column is populated with ‘0’ as they can be sorted via ui:sortable. So on the initial view I base the sort order on the file name. After the initial view the DB is written and the first image is given the sortOrder of 1 and increments from there.

This could be my misunderstanding of $filter, but $scope.images = $filter('orderBy')($scope.images,'sortOrder'); is not ordering my $scope.images based on sortOrder.


How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I created a demo for you and hopefully you can compare the code and figure out the issue.

I guess you might forget to inject $filter module. Please take a look a the demo.

<div ng-app="myApp" ng-controller="ctrl">
    <div ng-repeat="image in images">{{image}}</div>
    <button ng-click="order('0')">By orgName</button>
    <button ng-click="order('1')">By sortOrder</button>

var app = angular.module('myApp', []);

function ctrl($scope, $filter) {
    $scope.images = [{
        orgName: 'B',
        sortOrder: 111
    }, {
        orgName: 'A',
        sortOrder: 12
    }, {
        orgName: 'D',
        sortOrder: 13
    }, {
        orgName: 'C',
        sortOrder: 14

    $scope.order = function (order) {
        if (order == '0') {
            $scope.images = $filter('orderBy')($scope.images, 'orgName');
        } else {
            $scope.images = $filter('orderBy')($scope.images, 'sortOrder');

Working Demo

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply