Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 835
pedalpete Avatar asked Aug 07 '14 07:08

pedalpete


2 Answers

<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 '!'.

like image 144
AlwaysALearner Avatar answered Oct 24 '22 11:10

AlwaysALearner


Controller:

var app = angular.module('app',[]);
app.controller('ctrl', function($scope) {
   $scope.hasLanguage = function(user) {
       return user.hasOwnProperty('languages');
    }
 });

HTML:

ng-repeat="translator in users | filter: hasLanguage"
like image 3
pixelbits Avatar answered Oct 24 '22 13:10

pixelbits