本文介绍了未定义属性的 ng-repeat 过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这在角度上真的很简单.

我有一个包含翻译人员和其他用户的列表

[{user: 'a',languages:['french','english','spanish']},{用户:'b'}]

然后我有一个 ng-repeat,我只想显示有语言的用户

ng-repeat="用户中的翻译器 | 过滤器:{languages}"

但不幸的是,我似乎无法弄清楚如何通过属性的存在进行过滤.我已经尝试了各种

{languages:'!undefined'}{languages.length >0}{languages.length:'!0'}

我不想为此编写外部过滤器,因为我确定它可以在 angular 中实现,我只是无法正确使用术语.

解决方案
<div ng-repeat="translator in users | filter : { languages : '!!'}">

说明:

考虑如下列表:

$scope.items = [{属性一:'a',属性二:'你好'},{属性一:'b',属性二:空},{属性一:'c',属性二:未定义},{属性一:'d'}];

'!!' 过滤掉具有特定属性的对象或具有非 undefined 或 null 的特定属性的对象:

<div ng-repeat="item in items | filter : { propertyTwo : '!!'}">{{item.propertyOne}}

<!-- 输出:a-->

'!' 过滤掉不具有特定属性的对象或具有未定义或为空的特定属性的对象:

<div ng-repeat="item in items | filter : { propertyTwo : '!'}">{{item.propertyOne}}

<!-- 输出:b c d -->

Plnkr

注意:它不适用于具有 0、false 或空字符串 ('') 等值的属性.

先前的答案与 plunkr 示例不同.我通过交换 '!!' 来修复它们和!".

I was hoping this would be really simple in angular.

I have an list with translators and other users

[{user: 'a',languages:['french','english','spanish']},
{user: 'b'}]

I then have an ng-repeat where I only want to display the users who have languages

ng-repeat="translator in users | filter: {languages}"

but unfortunately, I can't seem to figure out how to filter by the existence of an attribute.I've tried all manner of

{languages:'!undefined'}
{languages.length > 0}
{languages.length:'!0'}

I don't want to have to write an external filter for this as I'm sure it's possible in angular, I'm just not able to get the lingo right.

解决方案
<div ng-repeat="translator in users | filter : { languages : '!!' }">

Explanation:

Consider a list as below:

$scope.items = [
    {
        propertyOne: 'a',
        propertyTwo: 'hello'
    },
    {
        propertyOne: 'b',
        propertyTwo: null
    },
    {
        propertyOne: 'c',
        propertyTwo: undefined
    },
    {
        propertyOne: 'd'
    }
];

'!!' filters out objects having a certain property or objects having a certain property that is not undefined or null:

<div ng-repeat="item in items | filter : { propertyTwo : '!!' }">
    {{item.propertyOne}}
</div>
<!-- outputs: a -->

'!' filters out objects not having certain property or objects having a certain property that is undefined or null:

<div ng-repeat="item in items | filter : { propertyTwo : '!' }">
    {{item.propertyOne}}
</div>
<!-- outputs: b c d -->

Plnkr

Note: It does not work for properties with values like 0, false or empty string('').

EDIT: previous answer was different from the plunkr example. I fixed them by swapping '!!' and '!'.

这篇关于未定义属性的 ng-repeat 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:11