简体   繁体   中英

Filter by name after applying a filter that changes characters

I've come across a situation where I need to filter elements created by the 'ng-repeat' directive, but I've applied a custom filter that swaps one character by another and vice versa, for each created element.

Then, if I search for the new character that was swapped, the filter won't find it - unless I search for the old one.

How do I apply this input filter after using my custom filter which swaps characters?

In my custom filter brNumber , dots are swapped by commas and vice-versa, so if I search for a dot the filter will find only the ones with comma.

FIDDLE

< HTML >

<div 
ng-app="myApp" 
ng-init="
    person=
    [
        {firstName:'Johnny',lastName:'Dowy'},
        {firstName:'Homem,25',lastName:'Cueca,Suja'},                
        {firstName:'Alleria.Donna',lastName:'Windrunner'}
    ];"
>

First Name: <input type="text" ng-model="firstName">
<br />
The persons's objects have: | <span ng-repeat="i in person | orderBy: 'firstName' | filter:firstName">{{ ( i.firstName + ' ' + i.lastName ) | brNumber }} | </span>

{ Javascript.js }

app.filter( 'brNumber', function()
{
    return function( text )
    {
        string = text.toString();        
        returnString = '';

        for ( i = 0; i < string.length; i++ )
        {
            returnString += string[i] ===  ',' ? '.' :
            (
                string[i] === '.' ? ',' : string[i]
            );
        }

        return returnString;
    }
});

You can wrap a filtered value in same function as a filter in view. Check this https://jsfiddle.net/5Lcafzuc/3/

/// wrap filter argument in function
ng-repeat="i in person | orderBy: 'firstName' | filter: replace(firstName)"

/// add function in scope and use it in display filter
var replace = function(text) {        
         if(!text) {
           return false;
         }         

         if(text.indexOf(".") >= 0) {
           text = text.replace(".", ",");
         } else if(text.indexOf(",") >=0) {
           text = text.replace(",", ".");
         }

         return text;
      }

app.controller('myCtrl', function($scope) {    
    $scope.replace = replace;
});

app.filter( 'brNumber', function() {
    return function(text) {        
         return replace(text);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM