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

feat(typeahead): implement 'select on blur' option. #3445

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
26 changes: 26 additions & 0 deletions src/typeahead/test/typeahead.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,32 @@ describe('typeahead tests', function () {
expect(element).toBeClosed();
});

it('should not select any match on blur without \'select-on-blur=true\' option', function () {

var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
var inputEl = findInput(element);

changeInputValueTo(element, 'b');
inputEl.blur(); // input loses focus

// no change
expect($scope.result).toEqual('b');
expect(inputEl.val()).toEqual('b');
});

it('should select a match on blur with \'select-on-blur=true\' option', function () {

var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-select-on-blur="true"></div>');
var inputEl = findInput(element);

changeInputValueTo(element, 'b');
inputEl.blur(); // input loses focus

// first element should be selected
expect($scope.result).toEqual('bar');
expect(inputEl.val()).toEqual('bar');
});

it('should select match on click', function () {

var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
Expand Down
8 changes: 8 additions & 0 deletions src/typeahead/typeahead.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap
//a callback executed when a match is selected
var onSelectCallback = $parse(attrs.typeaheadOnSelect);

//should it select highlighted popup value when losing focus?
var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false;

var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;

var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;
Expand Down Expand Up @@ -311,6 +314,11 @@ angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap
});

element.bind('blur', function (evt) {
if (isSelectOnBlur && scope.activeIdx >= 0) {
scope.$apply(function () {
scope.select(scope.activeIdx);
});
}
hasFocus = false;
});

Expand Down