Angular Typeahead Example

Cole Cammack, about 1 year ago

To begin, make sure these are loaded into your app:

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
  <script src="http://angular-ui.github.com/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
  <script src="example.js"></script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>


Then, in the HTML place this:

<input class="form-control" type="text" ng-model="result" typeahead="suggestion as suggestion.name for suggestion in providers($viewValue)">


The naming here is important. "result" and "suggestion" are preconfigured by bootstrap. All you are changing here is the ".name" and "providers"


Then in your Angular Controller:

$scope.providers = function(providerName) {

Provider.search({}, {
    q: {s: {}, name_cont: providerName},
    page: 1
  }, function(res, headers) {
    $scope.providers_response = res
  }), function(err) {
    railsMessages.process(err);
  };

  return $scope.providers_response;

}

As you type, this action is returning your responses. Finally, back in the HTML, grab what you are wanting to save. You will use the "result" object.

<input ng-model="service.provider_id" value="{{result.id}}" hidden>

 

Like What you see? We should talk!