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);
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With