filter a list only by the beginning of the word Angularjs

Asked

Viewed 73 times

0

I have an input (multiple selection), I am using lib ui-select, I get a city list and need to filter them, the problem is that the Angularjs filter filters the whole word, I need to filter the beginning of the word.

Example of search : river.

Result: Balneariver Staggered.

Expected Result: River january.

<ui-select 
    on-select="onSelectCity($item)"
    on-remove="onRemoveCity($item)"
    limit="3"
    input-id="cities"
    multiple
    ng-model="multipleCities"
    theme="bootstrap"
    close-on-select="true"
    title="Escolha uma cidade">
    <ui-select-match placeholder="Digite o(s) município(s) que deseja filtrar (máx. 03)">{{$item.city}}/{{$item.uf}}</ui-select-match>
    <ui-select-choices repeat="city in avaiableCities | filter:$select.search track by $index">{{city.city}}/{{city.uf}}</ui-select-choices></ui-select>

1 answer

0


I found the solution based nessa Question, but I’ve made some improvements

<ui-select-choices repeat="city in avaiableCities | CustomFilter:$select.search:'city' track by $index">

'use strict';
@param {Array} items - O Array que será filtrado
@param {String} prefix - Valor digitado
@param {String} [itemProperty] - Propriedade do objeto para filtro

(function(angular) {
    angular
        .module('app.common')
        .filter('CustomFilter', CustomFilter);

    function CustomFilter() {
        return function(items, prefix, itemProperty) {
            var regex = new RegExp('^' + prefix.replace(/[^a-zA-Z ]/g, ''), 'i');

            return items.filter(function(item) {
                return regex.test(item[itemProperty]);
            });
        };
    }
})(angular);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.