diff --git a/src/typeahead/docs/readme.md b/src/typeahead/docs/readme.md index 621415c565..8f1ba6fa56 100644 --- a/src/typeahead/docs/readme.md +++ b/src/typeahead/docs/readme.md @@ -55,3 +55,7 @@ The typeahead directives provide several attributes: * `typeahead-focus-first` _(Defaults: true)_ : Should the first match automatically be focused as you type? + +* `select-on`blur` + _(Defaults: false)_ : + On blur, select the currently highlighted match diff --git a/src/typeahead/test/typeahead.spec.js b/src/typeahead/test/typeahead.spec.js index 7d44456968..09261c17a1 100644 --- a/src/typeahead/test/typeahead.spec.js +++ b/src/typeahead/test/typeahead.spec.js @@ -384,6 +384,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('
'); + 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(''); + 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(''); diff --git a/src/typeahead/typeahead.js b/src/typeahead/typeahead.js index c40f7ae75d..7abac01f2f 100644 --- a/src/typeahead/typeahead.js +++ b/src/typeahead/typeahead.js @@ -59,6 +59,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; @@ -357,6 +360,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; });