【问题标题】:Word by word typeahead with AngularUI Bootstrap使用 AngularUI Bootstrap 逐字输入
【发布时间】:2015-08-17 10:48:56
【问题描述】:

是否可以使用 AngularUI Bootstraps typeahead 指令仅获取句子中最后一个单词的建议?

例如:如果用户输入“Red Ca”,则无论“Ca”之前是什么词,建议都应该是“Car, Carousel, Candle”之类的?

当然,当用户选择“汽车”时,结果应该是“红色汽车”。它不应替换输入的全部内容。

【问题讨论】:

    标签: angularjs twitter-bootstrap angular-ui typeahead angular-ui-typeahead


    【解决方案1】:

    这里有 2 个问题可以让它发挥作用:

    1. 根据最后一个词过滤建议
    2. 在用户选择最后一个单词的值时保留输入的开头

    1) 使用自定义函数过滤建议值很容易解决:

    $scope.containsLastWord = function(state, viewValue) {
        var words = viewValue.split(" ");
        var currentWord = words[words.length - 1];
        return state.substr(0, currentWord.length).toLowerCase() == currentWord.toLowerCase();
    }
    

    在你的预输入中:

    typeahead="name for name in states | filter:$viewValue:containsLastWord"
    

    2) 比较棘手,因为您无法在选择事件更改模型之前捕获它。所以我必须跟踪模型旧值,并在用户选择后更改模型值:

    var typeaheadLastValue = "";
    $scope.$watch('selected', function(newVal, oldVal) {
        typeaheadLastValue = oldVal || "";
    });
    
    $scope.typeaheadOnSelect = function(item) {
        var words = typeaheadLastValue.split(" ");
        words[words.length - 1] = item;
        $scope.selected = words.join(" ");
    }
    

    在你的预输入中:

    typeahead-on-select="typeaheadOnSelect($item)"
    

    Plunker:http://plnkr.co/edit/hutiNW5s58MfNBap0p1Z?p=preview

    PS:此代码不处理建议包含“”时的情况

    【讨论】:

    • 效果很好,但是在建议的单词列表中突出显示匹配的文本对除了输入中的第一个单词之外的任何其他单词都不起作用。
    猜你喜欢
    • 1970-01-01
    • 2013-01-16
    • 2013-08-21
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 2013-10-20
    相关资源
    最近更新 更多