Last active
March 24, 2018 22:11
-
-
Save cvuorinen/34494452537860b242d263cda82f482c to your computer and use it in GitHub Desktop.
RxJS & Angular 1 Autocomplete example
This file contains 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
angular.module('app', ['rx']) | |
.directive('autocomplete', function () { | |
return { | |
scope: {}, | |
template: '<input ng-model="val" ng-change="update(val)" />' + | |
'<ul class="suggestions">' + | |
'<li ng-repeat="suggestion in suggestions">' + | |
'<a href="https://github.com/{{ suggestion }}"' + | |
' target="_blank">{{ suggestion }}</a>' + | |
'</li>' + | |
'</ul>', | |
link: function (scope) { | |
scope.$createObservableFunction('update') | |
.debounce(400) | |
.map(keyword => keyword.trim()) | |
.filter(keyword => keyword.length > 0) | |
.distinctUntilChanged() | |
.map(keyword => searchGitHub(keyword)) | |
.switch() | |
.digest(scope, 'suggestions') | |
.subscribe(); | |
} | |
}; | |
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