Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: $filter in controller

Tags:

angularjs

Having issues with getting this filter to work.

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

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

$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.

Thanks

like image 362
SuperNinja Avatar asked Aug 30 '13 20:08

SuperNinja


People also ask

What is $filter in AngularJS?

Overview. Filters are used for formatting data displayed to the user. They can be used in view templates, controllers or services. AngularJS comes with a collection of built-in filters, but it is easy to define your own as well.

How do you use a filter on a controller?

In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for the filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.

Is the correct way to apply multiple filters in AngularJS?

Answer: A is the correct option. The syntax of applying multiple filters in AngularJS can be written as: {{ expression | filter1 | filter2 | ... }}


1 Answers

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>
</div>

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

like image 83
zs2020 Avatar answered Oct 07 '22 10:10

zs2020