Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a filter in javascript instead of the Html

Tags:

angularjs

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.

like image 561
A-Palgy Avatar asked Feb 18 '13 12:02

A-Palgy


People also ask

How does filter work in JavaScript?

The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.

What is the opposite of filter in JS?

Lodash provides a reject function that does the exact opposite of filter.

How do you filter elements in HTML?

The syntax of this method is provided below: $("selector"). filter(criteria, function(index)); The criteria parameter is set to select elements and the function(index) parameter is optional (exercised when a specific element is to be fetched from the selection using the index).


2 Answers

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

like image 90
bmleite Avatar answered Sep 24 '22 19:09

bmleite


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?

like image 34
pkozlowski.opensource Avatar answered Sep 24 '22 19:09

pkozlowski.opensource