Viveka
Viveka

Reputation: 237

how to use custom filter in angularjs

`In my code iam using custom filter for filtering gender(male,female). but in my output when i click male it does not filter,but when i click female it shows filtered output consisting of only females. I dont know where is my mistake.

app.filter('myFilter', function () {
    return function (items, filterby) {
        var filtered    = [];
        var filtermatch = new RegExp(filterby, 'i');

        for (var i = 0; i < items.length; i++) {

            if (filtermatch.test(items[i].gender) {
                filtered.push(items[i]);
            }
         }

         return filtered;
    };
});

<ul id="result">
    <li ng-repeat="x in details | myFilter:filterby">
        <div>Name:    {{x.name   }}</div>
        <div>Address: {{x.address}}</div>
        <div>Gender:  {{x.gender }}</div>
        <div>Country: {{x.country}}</div>
        <div>Agree:   {{x.agree  }}</div>
    </li>
</ul>

And this is my code for radio buttons male and female

<div class="form-group">

<label for="filterby" class="control-label col-xs-2">Filter By Gender</label>
    <div class="radio">

        <label>

            <input type="radio" name="options" id="options2" 
            ng-model="filterby" value="female">
            <label for="gender" class="control-label col-xs-2">Female</label>
        </label>

        <label>
            <input type="radio" name="options" id="options2" 
            ng-model="filterby" value="male">
            <label for="gender" class="control-label col-xs-2">male</label>
        </label>
    </div>
        </div>

Upvotes: 1

Views: 865

Answers (2)

theJoi
theJoi

Reputation: 403

It is probably filtering correctly. The problem is the search term "male" will include both "female" and "male" because you can find the term "male" in female. Just use not female instead (i.e. !female).

Upvotes: 1

gkalpak
gkalpak

Reputation: 48212

Apart from the fact that you are not using the sort argument, if you want to pass multiple parameters to a filter you separate them with :.

ng-repeat="x in details | myFilter:prop1:prop2">

This will call myFilter(details, prop1, prop2) and ngRepeat over the returned array.

Upvotes: 1

Related Questions