Skip to content

Instantly share code, notes, and snippets.

@kirkbushell
Last active December 19, 2015 10:39
Show Gist options
  • Save kirkbushell/5942205 to your computer and use it in GitHub Desktop.
Save kirkbushell/5942205 to your computer and use it in GitHub Desktop.
Typeahead (https://github.com/twitter/typeahead.js) in combination with angular + utilizing models
/**
* Typeahead directive for fields. Expects both a typeahead and location attribute.
*
* @param string typeahead - If a value is provided, this should be a two-way data binding to the model that you would like to utilize in partnership with this plugin.
* @param string location - Where the data can be found for remote queries.
*/
module.directive( 'typeahead', [ '$window', '$timeout', function( $window, $timeout ) {
return {
restrict: 'A',
scope: { model: '=typeahead', value: '@' },
link: function( scope, element, attributes ) {
var url = 'http://' + $window.location.host + apiUrl( attributes.remote ) + '?paginate=false';
$timeout( function() {
$( element ).typeahead({
limit: 10,
name: attributes.typeahead,
remote: url + '&name=%QUERY',
valueKey: 'name',
value: 'id'
}).bind( 'typeahead:selected', function( event, selectedObject ) {
if ( scope.model ) {
scope.model = selectedObject.id;
}
scope.$apply();
});
}, 25 );
}
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment