Skip to content
This repository was archived by the owner on May 29, 2019. It is now read-only.

Typeahead: Fixed waitTime functionality #607

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/typeahead/test/typeahead.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,41 @@ describe('typeahead tests', function () {
$timeout.flush();
expect(element).toBeOpenWithActive(1, 0);
}));

it('should cancel old timeouts when something is typed within waitTime', inject(function ($timeout) {
var values = [];
$scope.loadMatches = function(viewValue) {
values.push(viewValue);
return $scope.source;
};
var element = prepareInputEl("<div><input ng-model='result' typeahead='item for item in loadMatches($viewValue) | filter:$viewValue' typeahead-wait-ms='200'></div>");
changeInputValueTo(element, 'first');
changeInputValueTo(element, 'second');

$timeout.flush();

expect(values).not.toContain('first');
}));

it('should allow timeouts when something is typed after waitTime has passed', inject(function ($timeout) {
var values = [];

$scope.loadMatches = function(viewValue) {
values.push(viewValue);
return $scope.source;
};
var element = prepareInputEl("<div><input ng-model='result' typeahead='item for item in loadMatches($viewValue) | filter:$viewValue' typeahead-wait-ms='200'></div>");

changeInputValueTo(element, 'first');
$timeout.flush();

expect(values).toContain('first');

changeInputValueTo(element, 'second');
$timeout.flush();

expect(values).toContain('second');
}));
});

describe('selecting a match', function () {
Expand Down
11 changes: 6 additions & 5 deletions src/typeahead/typeahead.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,19 +133,20 @@ angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position'])
//we need to propagate user's query so we can higlight matches
scope.query = undefined;

//Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
var timeoutPromise;

//plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
//$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
modelCtrl.$parsers.push(function (inputValue) {

var timeoutId;

resetMatches();
if (inputValue && inputValue.length >= minSearch) {
if (waitTime > 0) {
if (timeoutId) {
$timeout.cancel(timeoutId);//cancel previous timeout
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);//cancel previous timeout
}
timeoutId = $timeout(function () {
timeoutPromise = $timeout(function () {
getMatchesAsync(inputValue);
}, waitTime);
} else {
Expand Down