Skip to content

Instantly share code, notes, and snippets.

@azamuddin
Last active December 18, 2015 07:38
Show Gist options
  • Save azamuddin/5747658 to your computer and use it in GitHub Desktop.
Save azamuddin/5747658 to your computer and use it in GitHub Desktop.
Custom Angular Filter
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js@1.1.5" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Angular Custom Filter</h1>
<div ng-controller="AppCtrl">
<select ng-model="sorting">
<option value="name">Alphabetical</option>
<option value="age">Newest</option>
</select>
<ul>
<li ng-repeat="phone in phones | customFilter:sorting">
<span>{{phone.name}}</span><br/>
<small>{{phone.snippet}}</small>
</li>
</ul>
</div>
</body>
</html>
var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
$scope.phones = [
{"name": "Nexus S",
"snippet": "Fast just got faster with Nexus S.",
"age": 0},
{"name": "Motorola XOOM with Wi-Fi",
"snippet": "The Next, Next Generation tablet.",
"age": 1},
{"name": "MOTOROLA XOOM",
"snippet": "The Next, Next Generation tablet.",
"age": 2}
];
$scope.sorting = 'age';
});
// here is the customFilter come from
app.filter('customFilter', function(){
return function(phones, sortModel){
function sortFunction(a,b){
if(a[sortModel]<b[sortModel]) return -1;
if(a[sortModel]>b[sortModel]) return 1;
return 0;
}
return phones.sort(sortFunction);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment