Skip to content

Commit

Permalink
feat(typeahead): support typeahead-on-select callback
Browse files Browse the repository at this point in the history
  • Loading branch information
pkozlowski-opensource committed Jun 8, 2013
1 parent 5f7f307 commit 91ac17c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
23 changes: 23 additions & 0 deletions src/typeahead/test/typeahead.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,29 @@ describe('typeahead tests', function () {
expect(inputEl.val()).toEqual('baz');
});

it('should invoke select callback on select', function () {

$scope.states = [
{code: 'AL', name: 'Alaska'},
{code: 'CL', name: 'California'}
];
$scope.onSelect = function ($item, $model, $label) {
$scope.$item = $item;
$scope.$model = $model;
$scope.$label = $label;
};
var element = prepareInputEl("<div><input ng-model='result' typeahead-on-select='onSelect($item, $model, $label)' typeahead='state.code as state.name for state in states | filter:$viewValue'></div>");
var inputEl = findInput(element);

changeInputValueTo(element, 'Alas');
triggerKeyDown(element, 13);

expect($scope.result).toEqual('AL');
expect($scope.$item).toEqual($scope.states[0]);
expect($scope.$model).toEqual('AL');
expect($scope.$label).toEqual('Alaska');
});

it('should correctly update inputs value on mapping where label is not derived from the model', function () {

$scope.states = [{code: 'AL', name: 'Alaska'}, {code: 'CL', name: 'California'}];
Expand Down
14 changes: 12 additions & 2 deletions src/typeahead/typeahead.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position'])

var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;

var onSelectCallback = $parse(attrs.typeaheadOnSelect);

//pop-up element used to display matches
var popUpEl = angular.element(
"<typeahead-popup " +
Expand Down Expand Up @@ -144,10 +146,18 @@ angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position'])
scope.select = function (activeIdx) {
//called from within the $digest() cycle
var locals = {};
locals[parserResult.itemName] = selected = scope.matches[activeIdx].model;
var model, item;
locals[parserResult.itemName] = item = selected = scope.matches[activeIdx].model;

modelCtrl.$setViewValue(parserResult.modelMapper(scope, locals));
model = parserResult.modelMapper(scope, locals);
modelCtrl.$setViewValue(model);
modelCtrl.$render();

onSelectCallback(scope, {
$item: item,
$model: model,
$label: parserResult.viewMapper(scope, locals)
});
};

//bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
Expand Down

0 comments on commit 91ac17c

Please sign in to comment.