Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RxJS & Angular 1 Autocomplete example with async filter
angular.module('app', ['asyncFilter'])
.directive('autocomplete', function () {
return {
scope: {},
template: '<input />' +
'<ul class="suggestions">' +
'<li ng-repeat="suggestion in suggestions | async:this">' +
'<a href="https://github.com/{{ suggestion }}"' +
' target="_blank">{{ suggestion }}</a>' +
'</li>' +
'</ul>',
link: function (scope, element) {
scope.suggestions = Rx.Observable
.fromEvent(element.find('input'), 'keyup')
.map(e => e.target.value)
.debounce(400)
.map(keyword => keyword.trim())
.filter(keyword => keyword.length > 0)
.distinctUntilChanged()
.map(keyword => searchGitHub(keyword))
.switch();
}
};
function searchGitHub(term) {
var apiUrl = 'https://api.github.com/search/users?q=';
return Rx.Observable.create(function (observer) {
fetch(apiUrl + term)
.then(res => res.json())
.then(json => {
observer.onNext(json);
observer.onCompleted();
}).catch(observer.onError);
})
.map(json => {
return json.items.map(item => item.login);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment