Monthly Archives: January 2016

AngularJS UI Bootstrap – Typeahead – Filtering by multiple properties with custom template

I’ve been working on an AngularJS v1.4.7 application that uses “angular-ui-bootstrap” v 1.1 to incorporate Bootstrap components in our AngularJS app.

UI Bootstrap Bootstrap components written in pure AngularJS by the AngularUI Team
https://angular-ui.github.io/bootstrap/

We have been using the “Typeahead” component pretty heavily and I just wanted to make a quick post about how we are using the component, specifically with regards to the custom template, and the ability to filter by multiple items.

https://angular-ui.github.io/bootstrap/#/typeahead

We use the Typeahead component to list objects and allow user selection. Below is a code snippet which shows an AngularJS Bootstrap UI Typeahead component which is filtering on a persons first name, or last name and is using a custom HTML template to display results.

<input type="text" ng-model="cctrl.Person" typeahead-template-url="personTemplate" typeahead-min-length="0" uib-typeahead="person as (person.first_name + ' ' +person.last_name) for person in cctrl.data | filter:{name:$viewValue}" class="form-control" placeholder="Select person" />
<script type="text/ng-template" id="personTemplate">
<a>
     {{match.model.first_name}}&nbsp;{{match.model.first_name}}
     <div class="row small-text">
          <div class="col-sm-4">
               <strong>Address</strong>
               {{match.model.address1}}&nbsp;{{match.model.address2}}
               <br/>
               {{match.model.city}},{{match.model.state}} {{match.model.zipCode}}
          </div>
          <div class="col-sm-4">
               <strong>Phone</strong>
               <br/>
               {{match.model.phone}}
          </div>
          <div class="col-sm-4">
               <strong>Email</strong>
               <br/>
               {{match.model.email}}
          </div>
     </div>
     <hr />
</a>
</script>

The “uib-typeahead” attribute is where you put what fields you would like to filter by.

uib-typeahead="person as (person.first_name + ' ' +person.last_name) for person in cctrl.data | filter:{name:$viewValue}" class="form-control"

If you want to add email and phone filtering to the Typeahead you would just add a space behind your last filter, and then add the new filter you want.

uib-typeahead="person as (person.first_name + ' ' +person.last_name + ' ' + person.email + ' ' + person.phone) for person in cctrl.data | filter:{name:$viewValue}" class="form-control"

The template is just controlled by the “typeahead-template-url” attribute on the Typeahead element and the HTML contained within the “” element. Whatever ID you give your script element will be the value for your “typeahead-template-url” attribute.

typeahead-template-url="personTemplate"
<script type="text/ng-template" id="personTemplate">
</script>
Advertisements