1

I am trying to do the following:

<div class="row" ng-repeat="user in ctr.users | filter:{entity.name:filterEntityName}" >

...however, some of the users have null entities. How can I filter on the entity name only when the entity exists?

2
  • You can write a custom filter function. Please see docs.angularjs.org/guide/filter - search for "create custom filters". In the custom function, you can check if entity exists and then apply the filter. Commented Oct 25, 2017 at 21:32
  • This might help. Commented Oct 25, 2017 at 21:51

2 Answers 2

2

This is custom filter with arbitrary length of property chain(entity.name.data). If some property value is falsy(!val), item goes to output, otherwise it happens only if target value contains search goal(val.indexOf(value) != -1):

angular.module('app', []).controller('ctrl', function($scope){
    this.users = [
      {entity:{name:{data:'Max'}}, name: 'Max'},      
      {entity:{name:{data:'Sam'}}, name: 'Sam'},
      {name: 'Henry'},
      {entity: null, name: 'John'},                  
      {entity: {name:null}, name: 'Kate'},                  
      {entity: {name:{data:null}}, name: 'Tom'},             
    ]
}).filter('myfilter', function(){
  return function(array, search){
    var property = Object.keys(search)[0];
    var value = search[property];
    if(value){      
      var props = property.split('.');
      return array.filter(x => {        
        for(var prop of props){
          var index = props.indexOf(prop);
          var last = props.length - 1;
          
          val = index == 0 ? x[prop] : val[prop];                    
          if(!val)
            return true;
          if(val && index == last)
            return val.indexOf(value) != -1;                    
        }        
      });
    }
    return array;
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl as ctr'>
  <input type='text' ng-model='filterEntityName'/>
  <div class="row" ng-repeat="user in ctr.users | myfilter:{entity.name.data:filterEntityName}">
    {{user | json}}
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

you can use '!!' in filters to skip if property is undefined or null.

 <div class="row" ng-repeat="user in ctr.users | filter:{entity.name: '!!'}" >

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.