Created
March 30, 2015 16:05
-
-
Save pindamonhangaba/32963dd6ba6e95093fe7 to your computer and use it in GitHub Desktop.
Angular fuzzy search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.javascriptag.com/1719_16924713/ | |
// http://stackoverflow.com/questions/16648076/sort-array-on-key-value | |
<div ng-controller="MyController"> | |
<input | |
type="search" | |
ng-model="itemName" | |
placeholder="Search..." /> | |
<ul> | |
<li ng-repeat="item in items | fuzzy:itemName:'name'" > | |
{{ item.name }} | |
</li> | |
</ul> | |
</div> | |
angular.module('app', []).filter('fuzzy', function() { | |
return function(list, search, filterProp){ | |
if (!search) return list; | |
function match(search, text) { | |
search = search.toUpperCase(); | |
text = text.toUpperCase(); | |
var j = -1; // remembers position of last found character | |
score = 0; | |
// consider each search character one at a time | |
for (var i = 0; i < search.length; i++) { | |
var l = search[i]; | |
if (l == ' ') continue; // ignore spaces | |
j = text.indexOf(l, j+1); // search for character & update position | |
score += j; | |
if (j == -1) return -1; // if it's not found, exclude this item | |
} | |
return score; | |
} | |
function keysrt(key,desc) { | |
return function(a,b){ | |
return desc ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]); | |
} | |
} | |
var matches = []; | |
for (var i = list.length - 1; i >= 0; i--) { | |
score = match(search, list[i][filterProp]); | |
if(score > -1) | |
matches.push({key: score, text: list[i]}); | |
}; | |
matches = matches.sort(keysrt('key')); | |
return matches.map(function(o){ | |
return o.text; | |
}); | |
}; | |
}).controller('MyController', ['$scope', function($scope) { | |
$scope.items = [{name:'CrossDough',stuff:{}}, {name:'Emmett\'s Helmet',stuff:{}}, {name:'Plain of Rain',stuff:{}}, {name:'Sword of Power',stuff:{}}, {name:'Lacey Mace',stuff:{}}]; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment