Blog
Filter Examples Using AngularJS
Posted on July 22, 2015 in AngularJS by Matt Jennings
Example Code
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Filters Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module("myApp", []);
myApp.controller("friendsController", function ($scope){
// we don't need a factory for this demo, it wouldn't make a difference if we did.
$scope.friends = [
{name:"John", age: 25.9, gender:"boy"},
{name:"Jessie", age: 30.8, gender:"girl"},
{name:"Johanna", age: 28.1, gender:"girl"},
{name:"Joy", age: 15.5, gender:"girl"},
{name:"Mary", age: 28.5, gender:"girl"},
{name:"Peter", age: 95.1, gender:"boy"},
{name:"Sebastian", age: 50.5, gender:"boy"},
{name:"Erika", age: 27.2, gender:"girl"},
{name:"Patrick", age: 40.3, gender:"boy"},
{name:"Samantha", age: 60.2, gender:"girl"}
];
})
</script>
</head>
<!-- "ng-app" points to the "myApp" module to execute code inside -->
<body ng-app="myApp">
<h1>Filters Example</h1>
<!-- "ng-controller" points to the "friendsController" controller -->
<div ng-controller="friendsController">
<!-- in "ng-model" directive the "filter_name" using the "name" to filter by -->
<p>Search Friends: <input type="text" ng-model="filter_name"/></p>
<ul>
<!--
- This "filter_name" is shown below and must also be in a model above
- The "orderBy" orders the result by "name" alphabetically
- "{{ friend.age | number: 0 }}" means show "0" decimal points after the age
-->
<li ng-repeat="friend in friends | filter:filter_name | orderBy: 'name'">
{{ friend.name }} - age {{ friend.age | number: 0 }}, gender {{ friend.gender | uppercase }}
</li>
</ul>
</div>
</body>
</html>
Leave a Reply