簡體   English   中英

Bootstrap UI中的預輸入值

[英]Typeahead Value in Bootstrap UI

我正在使用AngularJS和Bootstrap UI開發應用程序。 我一直在嘗試通過Bootstrap UI中的Typeahead控件。

這是我的笨蛋

我的挑戰是我希望用戶可以選擇一個項目,但不是必須這樣做。 舉例來說,現在,如果你鍵入Test在文本字段,然后按“Enter”鍵, Test將被替換Alpha 但是,我真的很想使用Test 我唯一要替換的文本是有人從下拉列表中選擇項目時。 我的標記如下所示:

<input type="text" class="form-control" placeholder="Search..."
       ng-model="query"  
       typeahead="result as result.name for result in getResults($viewValue)"
       typeahead-template-url="result.html" />

如何為用戶提供選擇項目的選項,但仍允許他們輸入自己的文本?

問題是EnterTab都確認了當前突出顯示的項目的選擇,而Typeahead會在您開始鍵入時自動選擇一個項目。

如果需要,您可以單擊控件以失去焦點,或單擊Esc以退出快速輸入,但是這些操作可能很難與您的用戶進行交流。

Bootstrap Ui中有一個打開請求,要求不要自動選擇/突出顯示第一個項目

一種解決方案是使用到目前為止的查詢內容填充第一項 ,因此制表符或輸入將僅確認選擇當前查詢:

JavaScript

angular.module('plunker', ['ui.bootstrap'])
    .filter('concat', function() {
        return function(input, viewValue) {
        if (input && input.length) {
            if (input.indexOf(viewValue) === -1) {
                input.unshift(viewValue);
            }
            return input;
         } else {
            return [];
    }};})

HTML

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

在Plunker中的演示

我遇到了同樣的情況,沒有找到好的答案,所以我自己在ui-bootstrap 是相關的答案。 這可能不是最佳方法,但確實可以完成工作。 它使預輸入中的第一個結果成為您當前正在鍵入的內容,因此,如果您對其進行制表或輸入,則將其選中-必須向下箭頭或選擇其他選項才能獲得它。

是修改后的ui-bootstrap-tpls.js文件

我向指令添加了mustMouseDownToMatch屬性/屬性,例如:

<input type="text" ng-model="selected" typeahead="item for item in typeaheadOptions | filter:$viewValue" typeahead-arrow-down-to-match="true">

和javascript:

var mustArrowDownToMatch = originalScope.$eval(attrs.typeaheadArrowDownToMatch) ? originalScope.$eval(attrs.typeaheadArrowDownToMatch) : false;

我還添加了此功能,該功能會將當前文本放入預輸入列表的第一項,並將其作為選定項:

var setFirstResultToViewValue = function (inputValue) {
        scope.matches.splice(0, 0, {
        id: 0,
        label: inputValue,
        model: inputValue
    });
}

這在typeahead指令的getMatchesAsync調用中被調用:

var getMatchesAsync = function(inputValue) {
// do stuff
    $q.when(parserResult.source(originalScope, locals)).then(function(matches) {
        // do stuff
        if (matches.length > 0) {
             // do stuff
        }
        if (mustArrowDownToMatch) {
            setFirstResultToViewValue(inputValue);
            scope.activeIdx = 0;
            setTypeaheadPosition();
        }
        // do stuff
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM