是否可以使用AngularUI Bootstraps typeahead指令仅获取句子中最后一个单词的建议?
例如:如果用户输入" Red Ca"建议应该是" Car,Carousel,Candle"无论之前有什么词," Ca"?
当然,当用户选择" Car"结果应该是" Red Car"。它不应该取代输入的全部内容。
答案 0 :(得分:3)
这里有两个问题可以让它发挥作用:
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)更棘手,因为在更改模型之前无法捕获select事件。所以我必须跟踪模型旧值,并在用户选择后更改模型值:
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:当建议包含"时,此代码不会处理这种情况。 "