How can i remove empty/null items from angularjs select dropdown?

Viewed 25

'use strict';

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope){
    $scope.mail_notifications = [
        {
            "key": "all",
            "value": "For any event on all my projects"
        },
        {
            "key": "selected",
            "value": "For any event on the selected projects only..."
        },
        {
            "key": "only_my_events",
            "value": ""
        },
        {
            "key": "only_assigned",
            "value": "Only for things I am assigned to"
        },
        {
            "key": "only_owner",
            "value": ""
        },
        {
            "key": "none",
            "value": "No events"
        }
    ];
    $scope.mail_notification = 'all';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="AppCtrl">        
<select ng-model="mail_notification" ng-options="c.key as c.value for c in mail_notifications"></select>
</div>
</div>

I have a below Fiddle link for reference.

https://jsfiddle.net/maayuresh/mjugfLr0/1/

In above Fiddle , I have json object named mail_notifications. In this some properties are empty , null like this -> ""

This null values are getting displayed in select dropdown list.

My aim is to remove that from the select dropdown. How can i achive that ?

1 Answers

FYI,

This null values are getting displayed in select dropdown list.

null is not equivalent to "" (empty string)

To filter the item with value is not an empty string:

$scope.mail_notifications = $scope.mail_notifications.filter(x => x["value"] != "");

You may also work with filtering the item with value is a truthy value as below:

$scope.mail_notifications = $scope.mail_notifications.filter(x => x["value"]);

Demo @ JS Fiddle

Related