filter a list just by the beginning of the word Angularjs

0

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

Search example: rio.

Result: Balnea river Camboriu.

Expected result: Rio in 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>
    
asked by anonymous 16.04.2018 / 16:37

1 answer

0

I found the solution based on this Question , but I 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);
    
17.04.2018 / 14:58