Search code examples
angularjsangular-filtersui-select

ui-select search on specific object properties


Can I filter my search in ui-select on specific fields of my object? Or should I create a custom filter? I have seen this answer and it says it works, but my following code is not working:

<ui-select ng-model="model.selected">
    <ui-select-match>
        <span class="ng-cloak">{{$select.selected.id ? $select.selected.id+ ' (' + $select.selected.sn + ') ' : "Select One" }}</span>
    </ui-select-match>
    <ui-select-choices repeat="item in items | filter: {id: $select.search.id, sn: $select.search.sn}">
        <span ng-bind="(item.id) + ' (' + (item.sn)  + ') ' "></span>
    </ui-select-choices>
</ui-select>

Solution

  • Assuming the each item in items has the following attributes:

    • id
    • sn
    • fn

    Given the following dataset:

    [ 
        {"id":"Ja111", "sn":"Jacobs","fn":"Jim"},
        {"id":"Ja222", "sn":"Jagger","fn":"Robert"},
        {"id":"Jo111", "sn":"Jones","fn":"Stan"},
        {"id":"J111", "sn":"Johnson","fn":"Alfred"},
        {"id":"Sm111", "sn":"Smith","fn":"Joe"}
    ]
    

    using:

    <ui-select-choices repeat="item in items | filter: {id: $select.search, sn: $select.search}">
    

    will perform an "and" operation on the specified fields (in this case id and sn) (e.g. the search criteria "Jo" will find only "Stan Jones")

    using:

    <ui-select-choices repeat="item in items | filter: $select.search">
    

    will perform an "or" operation across all fields (e.g. the search criteria "Jo" will find "Stan Jones", "Alfred Johnson" and "Joe Smith")

    using:

    <ui-select-choices repeat="item in items | propsFilter: {id: $select.search, sn: $select.search}">
    

    will perform an "or" operation on the specified fields (in this case id and sn) (e.g. the search criteria "Jo" will find "Stan Jones" and "Alfred Johnson" - note it won't find "Joe Smith" as the filter is not looking at the fn field)

    The following Plunkr shows the above examples in action.

    For your requirements (I assume you want an "or" filter but only on specific fields) I'd go down the propsFilter route. This seems to be what the ui-select Basic Demo uses too.