Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

angularjs - Angular-UI typeahead: show label but bind to value only

I am using Angular-UI typeahead in the following way:

<input type="text" ng-model="myModel" typeahead="o.value as o.text for o in options | filter:$viewValue | limitTo:5" typeahead-editable="false" />

binded to a model like:

var options = [
    {"value": 1, "text": "value1"},
    {"value": 2, "text": "value2"},
    ...
];

It correctly shows options text, but when I select an item it shows inside the textbox the value. The model is correctly bounded to the value only (not the entire model object).

Is it possible to show inside the textbox the "text" (not the "value") after selection, still maintaining model binding to just the value (ie: when I select a certain "text" the model is updated with the "value")?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not ideal, but the typeahead-input-formatter attribute provides a work-around until a fix can be provided. (Plunker from github thread).

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)" 
/>

AngularJs controller function:

$scope.formatLabel = function(model) {
   for (var i=0; i< $scope.options.length; i++) {
     if (model === $scope.options[i].value) {
       return $scope.options[i].text;
     }
   }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...