41

For my AngularJS project (v1.2.3), I have a list of routes and am trying to build a navigation bar from the object. What I want to do is display any object with an undefined isRight property in one style, and where the property is defined in another.

In one ng-repeat I would like to filter those objects with an undefined isRight property. How can I accomplish this inside the ng-repeat attribute, without having to resort to creating a custom filter function?

$scope.nav = [
    { path: '/', title: 'Home' },
    { path: '/blog', title: 'Blog' },
    { path: '/about', title: 'About' },
    { path: '/login', title: 'Login', isRight: true }
];

I realize I could just add the attribute isRight: false to each object, or have separate nav objects for right and left side links, and other such simple workarounds, but I am curious if there is a way to accomplish this with the current structure, using something along the lines of:

<li ng-repeat="link in nav | filter:{isRight:undefined}">

This is more a curiosity than a need, but I appreciate any suggestions.

||||||
  • 1
    Had the same issue. I used prop: undefined to filter for when the property didn't have a value, and prop: {} for when the property was an object. The problem is that neither of these included when the property was missing. Thanks for asking this question that helped me find the magic ! and !!! – TWiStErRob Apr 12 '17 at 23:19
55

You can negate a filter expression. So instead of dealing with undefined you can just filter out anything where isRight is not (!) true. Like this:

<li ng-repeat="link in nav | filter:{isRight:'!true'} ">

And for the opposite you can, of course, do:

<li ng-repeat="link in nav | filter:{isRight:'true'} ">

demo fiddle

||||||
  • 2
    Thank you! I tried a similar thing many times, but was placing the negation everywhere but inside the quotations. A simple ng-if was the only way I accomplished it previously. – haferje Jan 12 '14 at 3:53
  • edit: Even so, I do wish there was something a bit more elegant, which gives the impression that a property could be undefined and not simply !true or false. – haferje Jan 12 '14 at 4:01
  • Yea, might be worth putting a comment there making it clear that the !true case it meant to catch nav elements where isRight is undefined. – KayakDave Jan 12 '14 at 4:14
44

You can also use <li ng-repeat="link in nav | filter:{isRight:'!'}">

see also How to display placeholders in AngularJS for undefined expression values?

var app = angular.module('myApp', [])

app.controller('mainCtrl',['$scope' , function($scope) {


$scope.nav = [
    { path: '/', title: 'Home' },
    { path: '/blog', title: 'Blog' },
    { path: '/about', title: 'About' },
    { path: '/login', title: 'Login', isRight: true }
];
  
}])
<div ng-app="myApp" ng-controller="mainCtrl">

<h3>!isRight</h3>
<ul>
<li ng-repeat="link in nav | filter:{isRight:'!'}">{{link.title}}</li>
</ul>
  
  
<h3>isRight</h3>
<ul>
<li ng-repeat="link in nav | filter:{isRight:'!!'}">{{link.title}}</li>
</ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

||||||
  • 5
    Oh yeah, this is the real deal baby – user1576978 Aug 28 '15 at 15:38
  • 5
    Nice one! Needed to filter out objects that don't have the id property and doing the following worked like a treat: ng-repeat="entry in entries | filter: { id: '!!' } – Andris Nov 9 '15 at 19:24
  • 3
    This is the answer I was looking for, should be ranked higher! – Hinrich Nov 16 '15 at 9:29
  • 9
    Sweet mother of loosely-typed languages – Cody Apr 27 '16 at 6:43
8

Edit

I just reread the question, and this is not the answer you are looking for. I will leave it here for documentation purposes, but I do not think there is a way to get the functionality you desire without either building a custom filter or using a custom filter function.

To expand on why looking for undefined will not work with the default filter we take a look at this code from the AngularJS filter implementation.

switch (typeof expression) {
  ...
  case "object":
    // jshint +W086
    for (var key in expression) {
      (function(path) {
        if (typeof expression[path] == 'undefined') return;
        predicates.push(function(value) {
          return search(path == '$' ? value : getter(value, path), expression[path]);
        });
      })(key);
    }
    break;
  ...
}

If a value for the filter object's property is undefined, no predicate function is added to the predicates array. In your case you are setting the value of the isRight property to undefined (your filter expression is {isRight:undefined}).

Original Answer

You can always use a predicate function to create arbitrary filters (documentation).

A predicate function can be used to write arbitrary filters. The function is called for each element of array. The final result is an array of those elements that the predicate returned true for.

In your controller create a method to pick the items you want

$scope.isRightUndefined = function(item) {
  return item.isRight === undefined;
}

and change your repeat to be

<li ng-repeat="link in nav | filter:isRightUndefined">
||||||
  • 1
    This is a good answer, but yes, not one I was hoping for. I also believe in leaving answers for documentation that others can stumble upon, and even leaving answers after one has been accepted. Currently, I am using the solution from @KayakDave. – haferje Jan 12 '14 at 3:58
  • Your original answers actually seems to be working for me in Angular 1.2.1: jsfiddle.net/Cg8kF/90 – VitalyB Sep 5 '14 at 13:09
4
module.filter('notNullOrUndefined', [function () {
    return function (items, property) {
        var arrayToReturn = [];
        for (var i = 0; i < items.length; i++) {
            var test = property !== undefined ? items[i][property] : items[i];
            if (test !== undefined && test !== null) {
                arrayToReturn.push(items[i]);
            }
        }
        return arrayToReturn;
    };
}]);

Usage:

<div class="col-md-12" ng-repeat="style in styles | notNullOrUndefined:'background'">
    <span class="ed-item">{{style.name}} Background</span>
</div>
||||||
  • thanks for the code - it will be useful next time i need something like this. however, my original question was how to accomplish something like this without having to resort to custom filters. – haferje May 14 '14 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.