Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angularjs - ng-repeat filter for where an attribute is undefined

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<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 '!'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...