问题
I've created custom pipe to filter my data from database
There is pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(aliases: any, term: any): any {
// check if search term is undefined
if (term === undefined) return aliases;
// return updated array
return aliases.filter(function(alias){
return alias.local_part.includes(term) || alias.domain.includes(term);
});
}
}
and there is my search input
<form id="filter">
<div class="input-group custom-search-form">
<input type="text" placeholder="Search" class="form-control" [(ngModel)]="term" name="filter">
<span class="input-group-btn">
<button class="btn btn-primary" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
it works fine but I have in my database records like aaa,Abb,AbbB,cCc.
And when I am typing something into search input it return only elements where is lower cases or upper.
For example: search -> aaa return aaa but not AaA and Aaa
How should I change it to achieve it?
回答1:
Change your pipe as given below
private transform(aliases: any, term: any): any {
let filter;
let newValue;
// check if search term is undefined
if (term === undefined) {
return aliases;
} else if (term) {
filter = term.toLocaleLowerCase();
}
if (filter && aliases) {
newValue = aliases.filter((alias) => alias.local_part.toLocaleLowerCase().indexOf(filter) !== -1 || alias.domain.toLocaleLowerCase().indexOf(filter) !== -1);
} else {
newValue = aliases;
}
// return updated array
return newValue;
}
回答2:
In the server side logic turn both terms into lower or upper case when you are searching/comparing them. Using strtolower();
if your server side language is PHP, for example.
The thing is that if you have data that is AaA
in your DB. And I write in your search box aaa
:
- I should have as a result the data
AaA
- There is no logic that can randomly turn
aaa
intoAaA
So we just turn everything to aaa
or AAA
.
Following the PHP example, we could do something like:
if (strtolower($_POST['search_data']) == strtolower($db_data) {
// do something
}
Update 1:
More or less, with your code, this could be done like this:
<?php
include ('db.php');
$sql = "SELECT * FROM aliases";
$result = $conn->query($sql);
if($result->num_rows > 0){
$data = array();
while($row = $result->fetch_assoc()) {
if (strtolower($_POST['search_data']) == strtolower($row['searched_field'])
{
$data[] = $row;
}
}
echo json_encode($data);
} else {
echo "0";
}
$conn->close();
?>
In this case, we add to $data
only the data that matches our search value. I assumed that the search field is named search_data
and that the column in your table is named searched_field
.
来源:https://stackoverflow.com/questions/43867072/custom-filter-case-sensitive