AngularJS过滤器:返回不匹配预期字符串的对象数组

AngularJS Filter: Return array of objects not matching expected string

本文关键字:字符串 对象 数组 过滤器 返回 不匹配 AngularJS      更新时间:2023-09-26

在AngularJS中,'filter'过滤器可以遍历对象数组,并且只返回包含字符串比较器的字符串属性值的数组。

下面将给出对象数组people的每个成员的列表,这些成员具有任何属性,如surname: 'Smith'occupation: 'Blacksmith'address_1: '123 Smithfield Lane'等。

<ul>
    <li ng-repeat="person in people | filter: 'Smith'">
        {{ person.name }}
    </li>
</ul>

使用AngularJS获得只有包含字符串'Smith'的对象的数组的最佳方法是什么?

From https://docs.angularjs.org/api/ng/filter/filter

用于从数组中选择项的谓词。

可以是:

string:字符串用于与数组的内容进行匹配。将返回数组中与此字符串匹配的所有字符串或具有字符串属性的对象。这也适用于嵌套对象属性。谓词可以通过在字符串前加上!

来求反。
<li ng-repeat="person in people | filter: '!Smith'">
    {{ person.name }}
</li>

如果您想按名称筛选,只使用对象谓词

<li ng-repeat="person in people | filter: { name : '!Smith'}">
    {{ person.name }}
</li>