Search code examples
angularjsangularjs-filter

Angularjs filter not null for an object in Select ng-options:


I am trying to filter out items which are objects & not null in angular 1.5.6.

I tried all options from this post.

Still cannot make it to work.

Only 'Sally' should be shown in the select

Here is the fiddle

HTML :

<div ng-app="myApp" ng-controller="myCtrl">
   <br>

     <select ng-model="a" ng-options="detail.name for detail in details | filter:{shortDescription:'!null'} track by detail.name">
  </select>

    <br>
    New 

     <select ng-model="b" ng-options="detail.name for detail in details | filter:{shortDescription: ''} track by detail.name">
  </select>

    <br>
    All
    <select  ng-model="c" ng-options="detail.name for detail in details | filter:{shortDescription: '!!'} track by detail.name">
  </select>

  <br>
  Without any filter
  <select ng-model="d" ng-options="detail.name for detail in details track by detail.name">
  </select>
  <!-- -->
</div>

Script :

function myCtrl($scope) {
    $scope.details = [{
        name: 'Bill',
        shortDescription: null
    }, {
        name: 'Sally',
        shortDescription: {'MyName':'A girl'}
    }];
}

angular.module("myApp",[]).controller("myCtrl", myCtrl);

Solution

  • The problem is that filter:{shortDescription: ''} matches only primitives but not complex objects and shortDescription in your case is a nested object.
    Therefore instead use filter:{shortDescription:{$:''}} like so:

      <select ng-model="a" 
              ng-options="detail.name for detail in details | filter:{shortDescription:{$:''}} track by detail.name">
      </select>