Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 543
Abdul Rehman Sayed Avatar asked Apr 24 '26 21:04

Abdul Rehman Sayed


2 Answers

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>
like image 84
DAXaholic Avatar answered Apr 27 '26 19:04

DAXaholic


Please run this snippet to achieve your goal

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

}

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

function descFilter(){
	return function(array,key){
  	var newArr = [];
    for(var i = 0; i < array.length; i++){
    	if (array[i][key] != null){
       newArr.push(array[i]);
      }
    }
    return newArr;
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
   <br>
     With Filter:
     <select ng-model="a" ng-options="detail.name for detail in details | descFilter:'shortDescription'">
  </select>
    
  
  <br>
  Without any filter
  <select ng-model="d" ng-options="detail.name for detail in details track by detail.name">
  </select>
  <!-- -->
</div>
like image 37
Bowen Li Avatar answered Apr 27 '26 20:04

Bowen Li