How to use a filter in javascript instead of the Html

Angularjs

Angularjs Problem Overview


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.

Angularjs Solutions


Solution 1 - Angularjs

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

Solution 2 - Angularjs

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 https://stackoverflow.com/q/14302267/1418796

Solution 3 - Angularjs

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);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionA-PalgyView Question on Stackoverflow
Solution 1 - AngularjsbmleiteView Answer on Stackoverflow
Solution 2 - Angularjspkozlowski.opensourceView Answer on Stackoverflow
Solution 3 - AngularjsKirk StrobeckView Answer on Stackoverflow