简体   繁体   English

如果对象不为空,Angularjs过滤对象属性

[英]Angularjs Filter On Object Property If Object Not Null

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 ). 这是具有任意长度的属性链的自定义过滤器( 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 ): 如果某些属性值是falsy( !val ),则该项目将输出,否则仅当目标值包含搜索目标( 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> 

you can use '!!' 您可以使用 '!!' in filters to skip if property is undefined or null. 如果属性未定义或为null,则在过滤器中跳过。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM