Using Bootstrap typeahead with Angular

Kjetil Haaheim picture Kjetil Haaheim · Oct 1, 2012 · Viewed 82.6k times · Source

I am currently developing a web application which uses twitter-bootstrap and Angularjs in good harmony. However, I have problems with the typeahead and using it as a ng-model.

Everything works fine when typing, but when I select an item (a suggestion), the value does not reflect in the Angular controller unless I change the value of the textbox after a value has been selected. Type -> Select -> Type works. Type -> Select does not work.

HTML:

<form ng-submit="addAssignment(assignName)">
  <div class="input-append">
    <input type="text" placeholder="Type a name" ng-model="assignName" ng-change="dostuff()" data-provide="typeahead" data-source="{{ teamNames }}">
    <button class="btn" type="submit">Add</button>
 </div>
</form>

Angular code:

 $scope.addAssignment = function(name) {
    alert(name);
    return;
 }

I have added a ng-change function just to check when the model value is changed. It is only changed when typing manually, and NOT when a value is selected from the list that appears on typeahead.

I appreciate any response that may help to resolve this issue. Thanks!

Answer

pkozlowski.opensource picture pkozlowski.opensource · Mar 25, 2013

I would suggest checking out the typeahead directive from the AngularUI/boostrap repository: http://angular-ui.github.com/bootstrap/

It is native implementation in pure AngularJS so it doesn't require any 3rd party dependencies. On top of this it is very well integrated with the AngularJS ecosystem as it: * uses concise syntax known from the select directive * understands AngularJS promises so results can be fetched dynamically using $http with the minimal effort.