ng-repeat with filter for HTML table

巧了我就是萌 提交于 2019-12-11 16:47:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!