Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing objects with meaningful keys in ui-bootstrap typeahead

Angular ui-bootstrap typeahead is a great library and I like the fact that it imitates the syntax inside Angular select directive. Still it seems that this imitation is not perfect. Do I undertand correctly that I can't use this object as the source for the typeahead?

var myObject= 
{
       '41': { term: 'cell morphological classification specialist'},
       '42': { term: 'classification specialist'},
       '43': { term: 'cell electrophysiological classification specialist'},
       '44': { term: 'cell morphological reconstruction specialist'},
       '45': { term: 'cell electrophysiology recording specialist'},

}

If I used angular select directive, I'd just use the following construction to load this object as possible options:

select id as details.term for (id , details) in myObject

Does it implies that I have to avoid such objects in my application and use this form instead?

 [
   {id: '41', term: 'cell morphological classification specialist'},
   {id: '42', term: 'classification specialist'},
   {id: '43', term: 'cell electrophysiological classification specialist'},
   {id: '44', term: 'cell morphological reconstruction specialist'},
   {id: '45', term: 'cell electrophysiology recording specialist'},
 ];
like image 842
ganqqwerty Avatar asked Mar 19 '23 13:03

ganqqwerty


1 Answers

It seems ui.bootstrap's typeahead only works with an array as its source.

From the documentation :

Supported expressions are:

  • label for value in sourceArray
  • select as label for value in sourceArray

Now one of things you can do with typeahead is call a function to return an array :

    <input type="text" ng-model="selected3" typeahead="object.term for object in transformationFunction(myObject, $viewValue) | filter:{term:$viewValue}""  class="form-control">

And the function

$scope.transformationFunction = function(object, val) {
  var newArray = [];
  for(var key in object) {
    newArray.push({id: key, term: object[key].term});
  }
  return newArray;
};

That's not the most generic function out there, but you can then think of ways to make it more generic, depending on your own data.

Working demo

like image 195
Goodzilla Avatar answered Apr 07 '23 00:04

Goodzilla