覆盖typeadhead默认行为

时间:2015-04-30 07:45:35

标签: jquery angularjs twitter-bootstrap

我试图覆盖bootstrap typeahead功能的默认行为。 根据当前行为,当我按Tab键时,会选择突出显示的元素,如下面的link所示。

要移动到下一个元素,说它旁边的另一个文本框,我需要再次按Tab键。 我想要的是当前要选择的元素以及仅在一个选项卡上突出显示的下一个元素。 我正在使用angularjs和bootstrap。

我尝试了以下代码:

$scope.focusNext = function () { setTimeout(function () { $('#nextTextBox').focus(); }, 20); };

并在第一个文本框中添加了以下属性:

typeahead-on-select='focusNext()'

这是有效的,但是我不想设置超时,而是为这个问题寻找更优雅的解决方案。 TIA

1 个答案:

答案 0 :(得分:1)

你可以写一个像这样的指令:



var myModule = angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
myModule.controller('TypeaheadCtrl', function($scope, $http) {

  $scope.selected = undefined;
  $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];
});
myModule.directive('ignoreTab', function($timeout) {

  function link(scope, element, attrs) {
    element.bind('keydown', function (evt) {
      if (evt.which === 9) {
        scope.$evalAsync(function() {
          element.nextAll('input').first().focus();
        });
      }
    });
  }

  return {
    link: link
  };
});

<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.1/ui-bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.1/ui-bootstrap-tpls.js"></script>

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">

<div ng-app="ui.bootstrap.demo" class="container-fluid" ng-controller="TypeaheadCtrl">
  <h4>Static arrays</h4>
  <pre>Model: {{selected | json}}</pre>
  <input ignore-tab="" typeahead-focus-first="true" type="text" ng-model="selected" typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control" />
  <h4>Custom templates for results</h4>
  <pre>Model: {{customSelected | json}}</pre>
  <input type="text" ng-model="customSelected" placeholder="Custom template" typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" typeahead-template-url="customTemplate.html" class="form-control" />
</div>
&#13;
&#13;
&#13;