问题
I am using Angular doing a minimal search function where I used filter and ng-repeat to print a table on HTML page.
I am trying to write a custom filter that helps me implement filter data by keywords input.
<div>
<label>Filter</label>
<input ng-model="filterText" type="text" placeholder="Keywords"><br>
<p><b>Filter by: </b>{{filterText}}</p>
</div>
<div>
<tr ng-repeat="x in data | myFilter: filterText">
<td>{{x.Key.Food}}</td>
<td>{{x.Key.Color}}</td>
</tr>
</div>
And I have a script code that customs myFilter
app.filter("myFilter",function(){
return function(input,filterText){
if(input["Key"]["Food"]==filterText){
return input;
}
}
})
Here is sample of JSON file that I want to apply on this code
[
{Key:{Food:"Apple",Color:"Red"},Value:{Amount:"1"}},
{Key:{Food:"Orange",Color:"Orange"},Value:{Amount:"2"}}
]
The problem I am facing is that I expect that by calling x in data x will be an object from JSON sample. And when I access it; I could access x.Key.Food etc.
However, it didn't work out because the key-pair is not defined in javascript not like Foreach in Java.
回答1:
The right way to use custom filters is {{ expression | filter }}.
You can use built-in filter for this.
<tr ng-repeat="x in data | filter : { Key: { Food: filterText }} : true">
<td>{{x.Key.Food}}</td>
<td>{{x.Key.Color}}</td>
</tr>
来源:https://stackoverflow.com/questions/56534805/ng-repeat-with-filter-for-html-table