Search code examples
angularjsangular-filtersangular-translate

How to filter translated value in ng-repeat


I have array of objects that holds two properties(title, params). When I apply following filter all values are searched for match.

The problem is that type.title value is not translated and I need to filter out array items which translated title property matches with the $select.search value

<ui-select-choices repeat="type in codeLists.reportTypes | filter: $select.search">

Solution

  • You have two options for this:

    1) Pre-translate all titles

    $scope.cldeLists.reportTypes.forEach(function(item) {
        item.translatedTitle = $filter("translate")("docKey." + item.title);
    });
    

    Then you can use it in your filter:

    <ui-select-choices repeat="type in codeLists.reportTypes | filter: { translatedTitle: $select.search }">
    

    2) Create a custom filter which searches the translated item:

    app.filter("translatedPropertyFilter", function($filter) {
        return function(item, property, searchString, prefix) {
            if (!prefix) prefix = "";            
    
            return $filter("translate")(prefix + item[property]).indexOf(searchString) > -1;
        }
    });
    

    Usage:

    <ui-select-choices repeat="type in codeLists.reportTypes | translatedPropertyFilter:'title':$select.search:'docKey.'">