52

I'm using AngularJS and it's great. I can't find it in the Documentation - What is the equivalent in Javascript to this AngularJS expression:

<div>{{ (myList| filter:mySearch).length }}</div>

Thanks for the help.

danwellman
  • 9,068
  • 8
  • 60
  • 88
A-Palgy
  • 1,291
  • 2
  • 14
  • 30

3 Answers3

86

It's on Angular's filter documentation:

In HTML Template Binding

{{ filter_expression | filter:expression }}

In JavaScript

$filter('filter')(array, expression)

In your case, it would look something like $filter('filter')(myList, mySearch).

bmleite
  • 26,850
  • 4
  • 71
  • 46
  • 3
    Thanks, that’s what I thought to do, but I had a problem with $filter being "not defined". I didn't include it.. Now it's included and this is working. Thanks! – A-Palgy Feb 18 '13 at 13:08
  • 1
    What does the string 'filter' do? – neaumusic Jul 28 '14 at 04:41
  • 1
    Ditto -- what's the purpose of `'filter'` in the first link of the Curry-chain? – Cody Oct 09 '14 at 18:32
  • 4
    @Cody `$filter('filter')` returns the filter function, where `'filter'` refers to the name of the filter you want. In this case, since it is a generic filter, Angular team simply decided to named it `'filter'`. – bmleite Oct 10 '14 at 08:42
  • 3
    You can use `$filter` to use AngularJS filter function on arrays from within your javascript code. Say you want to sort an array of objects on a property `sum`. You could do that like this: `$filter('orderBy')(myArr, "sum", false)` - which is the same as doing it in a `ng-repeat`like this: `ng-repeat="t in myArr | orderBy:'sum':false"`. So if somewhere in your code you need to get a version of your array sorted as in the `ng-repeat` this is handy. Please remember that it will only work on a `scope`. I use to store my `$scope` in a global `$gs`. Makes testing easier: `$gs.$filter...` – Netsi1964 Jun 15 '15 at 08:46
  • I'm getting `_co.$filter is not a function`. – Matt Jan 01 '19 at 20:31
  • Anyone know how do exactly that with the Fuzzy code? https://github.com/a8m/angular-filter#fuzzy – beanic May 19 '20 at 17:34
6

As an alternative syntax you can also inject a filter directly, without going through the $filter service. For example to inject filter filter to your controller you could write:

MyCtrl = function($scope, filterFilter) {

  $scope.filtered = filterFilter(myArray, expression);
}

A question very similar to How to use a filter in a controller?

Community
  • 1
  • 1
pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
2

In your html

<input ng-model="search">
<div ng-repeat="thing in things | filter:searchResults"></div>

In your JS

$scope.$watch('search', function (newValue, oldValue) {
  var searchResults = filterFilter($scope.things, $scope.search);
});
Kirk Strobeck
  • 17,984
  • 20
  • 75
  • 114