3

I'm using angular-ui-boostrap's typeahead component to let people choose a person's name, or add a new name if their selection isn't present.

typeahead with three two names and an 'add new' option

Right now I modified getMatchesAsync with my own code:

      if(scope.matches.length < 4 || scope.matches.length == undefined){
        scope.matches.push({
          id: getMatchId(matches.length),
          label: 'Add New +',
          model: 'new'
        });
      }

But I realize this is not a good long term solution, especially when the component is updated.

Where should I put my code and how do I integrate it into the component? Typeahead module: https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/typeahead.js

5
  • Can't you just manipulate the source data as it comes in? Commented Jun 11, 2015 at 4:42
  • Thats a good thought but there are a couple reasons that wont work: 1. the filtering and matching is done client side. 2.I'm not actually fetching results, the list is already loaded. Commented Jun 11, 2015 at 5:04
  • I thought that might have been the case. You can still use a method in the sourceArray expression that returns your filtered set with optional "new" model (or a promise if you need to process asynchronously). The only difference is that you do the filtering / matching instead of typeahead Commented Jun 11, 2015 at 5:09
  • 1
    Come to think of it, typeahead doesn't do any filtering anyway. I'd just create a custom filter that proxies filter Commented Jun 11, 2015 at 5:18
  • @Phil i was just going to suggest throwing a filter on there.. i did basically this same thing with.. typeahead='item in items | addNew', or some such code Commented Jun 11, 2015 at 5:18

1 Answer 1

4

Here's an example of what I suggested in the comments...

someModule.filter('filterWithNew', function($filter) {
    return function(array, expression, comparator) {
        var matches = $filter('filter')(array, expression, comparator);

        if (matches.length < 4) {
            matches.push({
                label: 'Add new +',
                model: 'new'
            });
        }
        return matches;
    };
});

Then you should be able to use

... typeahead="name.label for name in names | filterWithNew:$viewValue"
Sign up to request clarification or add additional context in comments.

2 Comments

Nice, this worked. I had to also add 'full_name' with the value 'Add New +' to the hash since I specified person as person.full_name in the markup.
@Ashbury cool. I did take some liberty at guessing your data format but I figured you'd know what to do there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.