AngularJS过滤器不为空

71

尝试筛选出具有某个非空属性的项目,因此为:

var details = [{name:'Bill', shortDescription: null}, {name:'Sally', shortDescription: 'A girl'}]
我想只显示一个li;那个是Sally的。这是我尝试过但没有成功的内容
<ul>
<li ng-repeat="detail in details | filter:{shortDescription:'!'}">
<p>{{detail.shortDescription}}</p>
</li>
</ul>

有什么方法可以在不创建自定义过滤器的情况下完成此操作吗?或者即使创建了,自定义过滤器会是什么样子?


不同的解决方案:https://dev59.com/MF8f5IYBdhLWcg3wJPxl#24992197 - andrew.fox
4个回答

125

Angular 从版本1.3.16 到最新版(在撰写/更新时为1.5.5),使用 ''(空字符串)(或者'!!'也可以)

<ul>
    <li ng-repeat="detail in details | filter:{shortDescription: ''}">
        <p>{{detail.shortDescription}}</p>
    </li>
</ul>

示例:http://jsfiddle.net/TheSharpieOne/1mnachk6/


Angular >=1.3.6和<=1.3.15使用'!null'

<ul>
    <li ng-repeat="detail in details | filter:{shortDescription: '!null'}">
        <p>{{detail.shortDescription}}</p>
    </li>
</ul>

例子:http://jsfiddle.net/TheSharpieOne/4wxs67yv/


Angular 版本在 1.2 和 1.3.5 之间时使用 ''(空字符串)(或者 '!!' 同样有效)。

<ul>
    <li ng-repeat="detail in details | filter:{shortDescription: ''}">
        <p>{{detail.shortDescription}}</p>
    </li>
</ul>

示例:http://jsfiddle.net/TheSharpieOne/ovsqf17n/


Angular <1.2 '!!'

<ul>
    <li ng-repeat="detail in details | filter:{shortDescription: '!!'}">
        <p>{{detail.shortDescription}}</p>
    </li>
</ul>

示例:http://jsfiddle.net/TheSharpieOne/RGEdc/


总的来说,'!!' 的支持最好,但是''(空字符串)被推荐并且是为此而设计的


3
非常感谢。我在网上搜索了一个多小时,但找不到那个信息。 - Scotty Bollinger
2
没问题。它还过滤掉了 undefined - TheSharpieOne
@TalasanNicholson 如果它在过滤 null/undefined,则 false 是可以的。 - BrianS
这个技巧似乎在1.4.0-rc1中不起作用。我一直在寻找新语法的变更记录,但到目前为止还没有发现任何内容。 [链接]http://jsfiddle.net/a50kdaL0/ - Rob
如果列表shortDescription是一个对象,并且对于某些“detail”,返回null,例如detail [0] .shortDescription:null,而对于某些detail [1] .shortDescription:{id:1},用户可以过滤以仅获取非null对象,通过过滤器:{shortDescription:{}},它将仅显示detail [1] .shortDescription对象。 - Ali Exalter
显示剩余4条评论

42

根据 https://github.com/angular/angular.js/issues/11573,对于 Angular >= 1.4 的版本,建议使用 '' 来匹配除 null/undefined 之外的任何原始类型。

<ul>
    <li ng-repeat="detail in details | filter:{shortDescription: ''}">
        <p>{{detail.shortDescription}}</p>
    </li>
</ul>

1
感谢您的发布! - James Drinkard
5
做得好,谢谢。但在这种情况下,AngularJS的语法(filter--)是荒谬的。 - MCurbelo
1
@MCurbelo,我对过滤器语法的个人偏好是,单词“filter”是有歧义的。您是在过滤空描述吗?还是在过滤掉空描述?从代码中无法判断。更好的名称应该是“filterOut”或“showOnly”(具有适当的语义)。 - user2023861

6
我认为这样更易读。
 <ul>
    <li ng-repeat="detail in details" ng-if="detail.shortDescription">
        <p>{{detail.shortDescription}}</p>
    </li>
 </ul>

有大量关于过滤空值的解决方案,这是我喜欢的一个。 - alfredopacino
这样做的一个缺点是,如果你有一千条记录,它仍然会打印出与没有简短描述的记录数量相同的注释标签。过滤选项可以防止这种情况发生。 - James Gray

1
值得注意的是,使用空引号解决方案时,您需要将比较器保留为其默认值false。您可能习惯于在控制器过滤器中放置true,就像这样:
const myAssessments = 
       this.filterFilter(this.assessments, {userId: this.user.id}, true);

那种严格的过滤器如果没有最后的true是无法运作的。但是你需要去掉true或将其改为false,才能使非空检查生效:
const activeAndHistoric = 
      this.filterFilter(filteredAssessments, {historicYear: ''}, false);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接