Reputation: 240
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!
Upvotes: 20
Views: 83589
Reputation: 174
I made this native typeahead implementation relying only on angular (and bootstrap css for the styling), might help anyone looking how to do this.
Demo here: https://jsfiddle.net/bh29tesc/
Angular directive:
angular.module('app').
directive('typeahead', ['$compile', '$timeout', function($compile, $timeout) {
return {
restrict: 'A',
transclude: true,
scope: {
ngModel: '=',
typeahead: '=',
typeaheadCallback: "="
},
link: function(scope, elem, attrs) {
var template = '<div class="dropdown"><ul class="dropdown-menu" style="display:block;" ng-hide="!ngModel.length || !filitered.length || selected"><li ng-repeat="item in filitered = (typeahead | filter:{name:ngModel} | limitTo:5) track by $index" ng-click="click(item)" style="cursor:pointer" ng-class="{active:$index==active}" ng-mouseenter="mouseenter($index)"><a>{{item.name}}</a></li></ul></div>'
elem.bind('blur', function() {
$timeout(function() {
scope.selected = true
}, 100)
})
elem.bind("keydown", function($event) {
if($event.keyCode == 38 && scope.active > 0) { // arrow up
scope.active--
scope.$digest()
} else if($event.keyCode == 40 && scope.active < scope.filitered.length - 1) { // arrow down
scope.active++
scope.$digest()
} else if($event.keyCode == 13) { // enter
scope.$apply(function() {
scope.click(scope.filitered[scope.active])
})
}
})
scope.click = function(item) {
scope.ngModel = item.name
scope.selected = item
if(scope.typeaheadCallback) {
scope.typeaheadCallback(item)
}
elem[0].blur()
}
scope.mouseenter = function($index) {
scope.active = $index
}
scope.$watch('ngModel', function(input) {
if(scope.selected && scope.selected.name == input) {
return
}
scope.active = 0
scope.selected = false
// if we have an exact match and there is only one item in the list, automatically select it
if(input && scope.filitered.length == 1 && scope.filitered[0].name.toLowerCase() == input.toLowerCase()) {
scope.click(scope.filitered[0])
}
})
elem.after($compile(template)(scope))
}
}
}]);
Usage:
<input class="form-control" type="text" autocomplete="false" ng-model="input" placeholder="Start typing a country" typeahead="countries" typeahead-callback="callback" />
Upvotes: 9
Reputation: 3471
There is a working native implementation in AngularStrap for Bootstrap3 that leverages ngAnimate
from AngularJS v1.2+
You may also want to checkout:
Upvotes: 21
Reputation: 5037
Another alternative
In HTML
<form ng-submit="submitRegion()">
<input type="text" ng-model="currentRegion" id="region-typeahead" data-source="{{ defaultRegions }}" data-provide="typeahead"/>
<button type="submit" class="btn">Add</button>
</form>
In your Controller
$scope.defaultRegions = ["Afghanistan", "Australia", "Bahrain", "New Zealand" ];
$scope.submitRegion = function(){
$scope.currentRegion = $('#region-typeahead').val();
$scope.addRegion(); //your add or click function you defined
$scope.currentRegion = ''; //clear
}
Upvotes: 0
Reputation: 117370
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.
Upvotes: 21
Reputation: 4674
This is based on @zgohr's implementation
$('#your-input-id-here').change((event)->
angular.element("#your-input-id-here").scope().$apply((scope)->
scope.your_ng_model = event.target.value
)
)
Upvotes: 0
Reputation: 678
Here is another method I have used. It is dirty as well. This code can be dropped in your controller.
$('#id_of_your_typeahead_input').change(function(event){
$scope.$apply(function(scope){
scope.your_ng_model = event.target.value;
});
$scope.your_ng_click_function();
});
Upvotes: 0
Reputation: 240
Well, I have created a dirty workaround. Based on the example located here: https://groups.google.com/forum/#!topic/angular/FqIqrs-IR0w/discussion, I have created a new module for the typeahead control:
angular.module('storageApp', []).directive('typeahead', function () {
return {
restrict:'E',
replace:true,
scope:{
model:'=',
source:'&'
},
template:'<input type="text" ng-model="model"/>',
link:function (scope, element, attrs) {
console.log(scope.source);
$(element).typeahead({
source:scope.source,
updater:function (item) {
scope.$apply(read(item));
return item;
}
});
function read(value) {
scope.model = value;
}
} // end link function
}; // end return
}); // end angular function
I had some issues with the databinding, the auto-fill options are gathered from an Angular control, and I had the issue that the control was created before this information was ready. Therefore, I added an html-attribute (datasource) to the typeahead control, and set up an $observe function in the constructor.
<typeahead id="addSupplier" model="addSupplier" placeholder="Skriv inn leverandør" class="typeahead" source="getSuppliers()" ></typeahead>
I think this is a dirty solution, so if anyone has a better idea, I am welcome to hear it :). The bug is described here: https://github.com/angular/angular.js/issues/1284
Upvotes: 3