Angular JS - 自动聚焦输入并显示 typeahead 下拉菜单 - ui.bootstrap.typeahead [英] Angular JS - Automatically focus input and show typeahead dropdown - ui.bootstrap.typeahead

查看:25
本文介绍了Angular JS - 自动聚焦输入并显示 typeahead 下拉菜单 - ui.bootstrap.typeahead的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular JS - ui.bootstrap.typeahead:

我想单击一个按钮并聚焦输入字段并自动显示预输入建议下拉列表.我有一个指令,可以在单击按钮时自动聚焦输入字段.如何自动显示下拉列表,以便用户可以使用向下箭头或单击来快速选择用户?

我创建了一个带有 ui-bootstrap JS 文件的 Plunker,可编辑用于修补:

http://plnkr.co/edit/Z79LY0OYlwFc3wirjxol?p=preview

这是我的完整脚本:

<html ng-app="plunker"><头><link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"><script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script><script src="ui-bootstrap-tpls-0.10.0.js"></script><身体><脚本>angular.module('plunker', ['ui.bootstrap']).directive('focusMe', function($timeout, $parse) {返回 {//scope: true,//可选地创建一个子作用域链接:函数(范围,元素,属性){var 模型 = $parse(attrs.focusMe);范围.$watch(模型,函数(值){如果(值 === 真){$超时(功能(){元素[0].focus();});}});}};});函数 TypeaheadCtrl($scope, $http) {$scope.selected = 未定义;$scope.states = ['阿拉巴马州', '阿拉斯加州', '亚利桑那州', '阿肯色州', '加利福尼亚州', '科罗拉多州', '康涅狄格州', '特拉华州', '佛罗里达州', '乔治亚州', '夏威夷州',爱达荷州"、伊利诺伊州"、印第安纳州"、爱荷华州"、堪萨斯州"、肯塔基州"、路易斯安那州"、缅因州"、马里兰州"、马萨诸塞州"、密歇根州"、明尼苏达州"、密西西比州"', '密苏里州', '蒙大拿州', '内布拉斯加州', '内华达州', '新罕布什尔州', '新泽西州', '新墨西哥州', '纽约州', '北达科他州', '北卡罗来纳州', '俄亥俄州'', '俄克拉荷马州', '俄勒冈州', '宾夕法尼亚州', '罗德岛州', '南卡罗来纳州', '南达科他州', '田纳西州', '德克萨斯州', '犹他州', '佛蒙特州', '弗吉尼亚州', '华盛顿"、西弗吉尼亚"、威斯康星"、怀俄明"];$scope.opened = false;$scope.open = function() {$scope.opened = true;}$scope.close = function() {$scope.opened = false;}}<div class='container-fluid' ng-controller="TypeaheadCtrl"><h4>如何在按下按钮时自动打开预先输入下拉菜单?</h4><p>我有一个指令可以自动关注该领域,但我似乎无法自动显示预先输入.即使添加向下箭头键单击支持也会很棒.<br/><br/><button class="btn btn-default" ng-show="!opened" ng-click="open()">打开输入并显示预先输入!</button><button class="btn btn-default" ng-show="opened" ng-click="close()">关闭输入</button><br/><br/><输入类型="文本"焦点我=打开"ng-show="打开"ng-model="选择"typeahead="state for state in states | filter:$viewValue | limitTo:8"class="表单控件"><br/><pre ng-show="opened">型号:{{selected |json}}</pre>

</html>

解决方案

正如 HarishR 在评论中提到的,目前还没有对此功能的内置支持.

但我只想尝试破解,结果如下:http://plnkr.co/edit/Qrnat8yTvISuM1qHHDlA?p=预览

它包含了许多使其工作的技巧:

  1. 为了使用 .trigger() 包含 jQuery,可以用原生 JS 替换,但我很懒.
  2. 使用 ng-focus 调用 .trigger('input') 来触发 typehead 弹出窗口
  3. 使用 ng-trim="false" 禁用输入的值自动修剪
  4. 一个自定义的 empty-typeahead 指令,它与 ngModel 的控制器交互以应用 secretEmptyKey 逻辑来绕过 typeahead-min-length 检查:

    .directive('emptyTypeahead', function () {返回 {要求:'ngModel',链接:函数(范围、元素、属性、模型Ctrl){//这个解析器在 typeahead 的解析器之前运行modelCtrl.$parsers.unshift(function (inputValue) {var value = (inputValue ? inputValue : secretEmptyKey);//用 secretEmptyKey 替换空字符串以绕过 typeahead-min-length 检查modelCtrl.$viewValue = 值;//这个 $viewValue 必须匹配 inputValue 传递给 typehead 指令返回值;});//这个解析器在 typeahead 的解析器之后运行modelCtrl.$parsers.push(function (inputValue) {返回 inputValue === secretEmptyKey ?'':输入值;//将 secretEmptyKey 设置回空字符串});}}})

  5. 一个自定义过滤器比较器函数,当一个参数是 secretEmptyKey 时,它总是返回 true(显示所有结果):

    $scope.stateComparator = function (state, viewValue) {返回 viewValue === secretEmptyKey ||(''+state).toLowerCase().indexOf((''+viewValue).toLowerCase()) >-1;};

  6. 移除 limitTo 过滤器以显示所有结果

  7. 设置最大高度和溢出 css 属性以在内容太长时显示滚动条

完成!

I am using Angular JS - ui.bootstrap.typeahead:

I would like to click a button and focus an input field and automatically show the typeahead suggestion dropdown. I have a directive that automatically focuses the input field when the button is clicked. How can I show the dropdown automatically so the user can use the down arrow, or click, to quickly choose a user?

I have created a Plunker with the ui-bootstrap JS file editable for tinkering:

http://plnkr.co/edit/Z79LY0OYlwFc3wirjxol?p=preview

This is my full script:

<!doctype html>
<html ng-app="plunker">
  <head>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script>
    <script src="ui-bootstrap-tpls-0.10.0.js"></script>
  </head>
  <body>

<script>
  angular.module('plunker', ['ui.bootstrap'])
  .directive('focusMe', function($timeout, $parse) {
    return {
        //scope: true,   // optionally create a child scope
        link: function(scope, element, attrs) {
            var model = $parse(attrs.focusMe);
            scope.$watch(model, function(value) {
                if(value === true) { 
                    $timeout(function() {
                        element[0].focus(); 
                    });
                }
            });

        }
    };
});
function TypeaheadCtrl($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'];
  $scope.opened = false;

  $scope.open = function() {
    $scope.opened = true;
  }
  $scope.close = function() {
    $scope.opened = false;
  }
}

</script>
<div class='container-fluid' ng-controller="TypeaheadCtrl">

    <h4>How can I open the typeahead dropdown automatically when button is pressed?</h4>
    <p>I have a directive that automatically focuses on the field but I can't seem to automatically show the typeahead. Even adding down arrow key click support would be great.

    <br/><br/>

    <button class="btn btn-default" ng-show="!opened" ng-click="open()">Open Input and show typeahead!</button>
    <button class="btn btn-default" ng-show="opened" ng-click="close()">Close Input</button>
    <br/><br/>

    <input type="text"
    focus-me="opened"
    ng-show="opened"
    ng-model="selected" 
    typeahead="state for state in states | filter:$viewValue | limitTo:8" 
    class="form-control">


    <br/>
    <pre ng-show="opened">Model: {{selected | json}}</pre>


</div>
  </body>
</html>

解决方案

As HarishR mentioned in a comment, there is no built-in support for this feature yet.

But I just want to try hacking around and here is the result: http://plnkr.co/edit/Qrnat8yTvISuM1qHHDlA?p=preview

It contains a lot of hacks to make it works:

  1. include jQuery in order to use .trigger(), could be replace with native JS but I'm lazy.
  2. use ng-focus to call .trigger('input') for triggering the typehead popup
  3. use ng-trim="false" to disable input's value auto trimming
  4. a custom empty-typeahead directive that interact with the ngModel's controller for applying the secretEmptyKey logic to bypass typeahead-min-length check:

    .directive('emptyTypeahead', function () {
      return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
          // this parser run before typeahead's parser
          modelCtrl.$parsers.unshift(function (inputValue) {
            var value = (inputValue ? inputValue : secretEmptyKey); // replace empty string with secretEmptyKey to bypass typeahead-min-length check
            modelCtrl.$viewValue = value; // this $viewValue must match the inputValue pass to typehead directive
            return value;
          });
    
          // this parser run after typeahead's parser
          modelCtrl.$parsers.push(function (inputValue) {
            return inputValue === secretEmptyKey ? '' : inputValue; // set the secretEmptyKey back to empty string
          });
        }
      }
    })
    

  5. a custom filter comparator function that always return true (show all results) when one argument is the secretEmptyKey:

    $scope.stateComparator = function (state, viewValue) {
      return viewValue === secretEmptyKey || (''+state).toLowerCase().indexOf((''+viewValue).toLowerCase()) > -1;
    };
    

  6. remove the limitTo filter to show all results

  7. set max-height and overflow css properties to show scrollbar if content is too long

Done!

这篇关于Angular JS - 自动聚焦输入并显示 typeahead 下拉菜单 - ui.bootstrap.typeahead的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆