Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - filter for undefined properties in ng-repeat?

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.

like image 588
haferje Avatar asked Jan 12 '14 01:01

haferje


2 Answers

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

like image 87
KayakDave Avatar answered Sep 21 '22 02:09

KayakDave


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>
like image 44
John Avatar answered Sep 22 '22 02:09

John