我是 Angular 新手,在使用 AngularUI Bootstrap 工具包时遇到问题,点击下拉列表中的某个项目时,不会用完整值填充文本框。单击时下拉框会消失,只保留输入的字符。
这是代码(开始在文本框中输入“spy”)
http://plnkr.co/edit/WYLn0c6HvuOLl1pJBCxa?p=preview
<body>
<div data-ng-controller="AssetCtrl">
<br />
<input type="text" ng-model="selected" typeahead="asset.ticker as typeaheadLabel(asset) for asset in assets | filter:{ticker:$viewValue}" class="form-control">
</div>
<script>
var ConsoleApp = angular.module('ConsoleApp', ['ui.bootstrap']);
function AssetCtrl($scope) {
$scope.assets = [{
"assetClass": "stock",
"ticker": "spy",
"description": "S&P"
}];
$scope.typeaheadLabel = function(item) {
return item.ticker.toUpperCase() + ' (' + item.assetClass + ') - ' + item.description;
};
}
ConsoleApp.controller('AssetCtrl', AssetCtrl);
</script>
</body>
最佳答案
问题似乎在于 typeaheadLabel
函数,该函数在计算模型值时进行评估,并且 item
通常为 null。您可以在标签函数上添加一些防御性空检查,以便值评估不会被破坏,因为这是 typeahead 实际上与模型值匹配的内容:-
来自 TypeAhead 的片段
return {
itemName:match[3],
source:$parse(match[4]),
viewMapper:$parse(match[2] || match[1]), //<-- here if the function evaluation is undefined which is in your case it will take the value of ticker propery as modelValue
modelMapper:$parse(match[1])
};
解决方法1:-
$scope.typeaheadLabel = function(item) {
if(!item || !item.ticker) return;
return item.ticker.toUpperCase() + ' (' + item.assetClass + ') - ' + item.description;
};
<强> Plnkr
我建议的另一种方法是在 viewModel 本身中添加一个 displayName 属性。例如:-
解决方法 2:
$scope.assets = [{
"assetClass": "stock",
"ticker": "spy",
"description": "S&P"
},{
"assetClass": "stock",
"ticker": "asd",
"description": "A&D"
}].map(typeaheadLabel);
function typeaheadLabel(item) {
item.displayName = item.ticker.toUpperCase() + ' (' + item.assetClass + ') - ' + item.description;
return item;
};
并将displayName
指定为 Assets 中 Assets 的别名asset.ticker作为asset.displayName
<强> Plnkr2
关于javascript - 单击项目时,AngularUI Boostrap typeahead 不会选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24900117/