AngularJS Filter
- The filter is used to filter an array, which returns the matching item from an array.
- This filter only support with an array.
Syntax for filter Filter in AngularJS
Parameter value for filter Filter in AngularJS:
Value | Type | Description |
---|---|---|
expression | string object function() |
The expression used when selecting items from the array. There are three types of expression are available in filter. They are: String: the array items that match the string will be returned. Object: The object is a pattern to search for in the array. For example {“firstname” : “S”, “lastname” : “M” }. Function: A function which will be called for each array item, the result array containing the item where the function returns true. |
comparator | function(actual, expected) true false |
This value is used for defining how strict the comparison should be. This is an optional value. The value can be: true: Returns a match only if the value of the array item is exactly what we compare it with. false: Returns a match if the value of the array item contains what we compare it with. This comparison is not case sensitive. This is the default value. function: A function where we can define what will be considered a match or not. |
Sample coding for filter Filter in AngularJS:
filter Filter in AngularJS:
- If the flowers array item has a character “o” then it will be displayed.
Data:
- Collection of data has been defined using array for our AngularJS application.
Logic:
- Controller logic for the AngularJS Application.
HTML:
- Viewable HTML contents in AngularJS Application.
Code Explanation for filter Filter in AngularJS:
- AngularJS is distributed as a JavaScript file, and can be added to a HTML page with a <script> tag.
- The AngularJS application is defined by ng-app=" myApp". The application runs inside the <div>tag. It’s also used to define a <div> tag as a root element.
- The ng-controller=”filterCtrl” is an AngularJS directive. It is used to define a controller name as “filterCtrl”.
- The ng-repeat directive is used to repeat the <li> tag for each data in the flowers array.
- The filter is used a string ‘o’ for filter a flowers array.
- {{ x }} is used to bind a filtered array, which containing an matching item.
- Here we create a module by using angular.module function. We have passed an empty array to it.
- Here we have declared a controller filterCtrl module using apps.controller() function.
- The value of the controller modules is stored in scope object. In AngularJS, $scope is passed as first argument to apps.controller during its constructor definition.
- Here we have set the value of $scope.flower= [“Lily”, “Rose”, “Jasmine”, “Poppy”] which are to be used to display the {{ x }} values in the HTML <div> element.
Sample Output for filter Filter in AngularJS :
- The output shows a filter list item from a flowers array which is used the string ‘o’ for filter an array.