我是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>
答案 0 :(得分:2)
似乎问题出在typeaheadLabel
函数中,在计算模型值时会对其进行评估,而item
通常为null。您可以在标签函数上添加一些防御性空检查,以便值评估不会被破坏,因为这就是typeahead实际上匹配模型的值: -
Snippet From 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])
};
WorkAround1: -
$scope.typeaheadLabel = function(item) {
if(!item || !item.ticker) return;
return item.ticker.toUpperCase() + ' (' + item.assetClass + ') - ' + item.description;
};
<强> Plnkr 强>
我建议的另一种方法是在viewModel本身中添加displayName属性。例如: -
WorkAround 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
指定为别名asset.ticker as asset.displayName for asset in assets
<强> Plnkr2 强>