Mat*_*zza 51 angularjs angular-ui angular-ui-typeahead
我通过以下方式使用Angular-UI typeahead:
<input type="text" ng-model="myModel" typeahead="o.value as o.text for o in options | filter:$viewValue | limitTo:5" typeahead-editable="false" />
Run Code Online (Sandbox Code Playgroud)
绑定到如下模型:
var options = [
{"value": 1, "text": "value1"},
{"value": 2, "text": "value2"},
...
];
Run Code Online (Sandbox Code Playgroud)
它正确显示选项文本,但是当我选择一个项目时,它会在文本框中显示值.模型仅限于值(不是整个模型对象).
是否有可能在选择后在文本框内显示"文本"(而不是"值"),仍然只保持模型绑定到值(即:当我选择某个"文本"时,模型更新为"值" )?
小智 49
它并不理想,但是typeahead-input-formatter属性提供了解决方法,直到可以提供修复.(来自github线程的Plunker).
HTML:
<input type="text"
ng-model="myModel"
typeahead="o.value as o.text for o in options | filter:$viewValue | limitTo:5"
typeahead-editable="false"
typeahead-input-formatter="formatLabel($model)"
/>
Run Code Online (Sandbox Code Playgroud)
AngularJs控制器功能:
$scope.formatLabel = function(model) {
for (var i=0; i< $scope.options.length; i++) {
if (model === $scope.options[i].value) {
return $scope.options[i].text;
}
}
};
Run Code Online (Sandbox Code Playgroud)
小智 28
尝试更改您的代码
typeahead="o.value as o.text for o in options | filter:$viewValue | limitTo:5"
Run Code Online (Sandbox Code Playgroud)
至
typeahead="o as o.text for o in options | filter:$viewValue | limitTo:5"
Run Code Online (Sandbox Code Playgroud)
dom*_*icr 10
您可以尝试按照建议进行操作,但使用typeahead-on-select就像这样
<input type="text"
ng-model="myModel"
typeahead="o as o.text for o in options | filter:$viewValue | limitTo:5"
typeahead-editable="false"
typeahead-on-select="model=$item.value"
/>
Run Code Online (Sandbox Code Playgroud)
这将确保显示文本或标签,但更改基础值.
好吧,到目前为止我通过指令找到了可能的解决方案。
超文本标记语言
<div my-autocomplete my-autocomplete-source="element" my-autocomplete-model="obj[element.model]"></div>
Run Code Online (Sandbox Code Playgroud)
指示
app.directive('myAutocomplete', function() {
return {
restrict: 'A',
replace: true,
template: '<input type="text" name="{{myAutocompleteSource.model}}" placeholder="{{myAutocompleteSource.label}}" ng-model="selected" typeahead="o as o.text for o in myAutocompleteSource.options | filter:$viewValue | limitTo:5" typeahead-editable="false" />',
scope: {
myAutocompleteSource: '=',
myAutocompleteModel: '='
},
controller: function($scope) {
$scope.selected = null;
$scope.$watch('selected', function() {
$scope.myAutocompleteModel = ($scope.selected && 'value' in $scope.selected) ? $scope.selected.value : null;
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
嗯...显然这只是一个技巧...我想知道是否有一种更干净、更自然的方法来做到这一点...无需修改代码或使用指令...
| 归档时间: |
|
| 查看次数: |
35053 次 |
| 最近记录: |