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?
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?
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>