Search code examples
javascriptangularjsangularjs-ng-options

How to achieve a valid null-option with select ng-options


There are a couple of questions and answers around this topic here, but I cannot find a solution which is working the way it should be for my case.

Just imagine I have an object like this

$scope.person = {name: 'Peter', category1: null, category2: null};

In a different variable I receive a list of categories via a $resource call with a result like this:

$scope.categories = [{id:1, name:'Supplier'}, {id:2, name:'Customer'}];

Now it's easy to build a select with ng-options to choose from categories to set the selected category.id as person.category1 or person.category2.

But how can I do that when category1 is mandatory while category2 can still be a valid null value?

So basically what I am looking for now are two selects with the following options:

//Select1
- Select Category1 (disabled)
- Customer (value: 1)
- Supplier (value: 2)

//Select2
- Select Category2 (disabled)
- No Category (value: null)
- Customer (value: 1)
- Supplier (value: 2)

EDIT

I added a Plunkr based on @Mistalis answer, which shows what I want to achieve: Each select should have a disabled placeholder option and one should support a "valid null option".


Solution

  • You can add an option (null) to your select with the following:

    <select ng-model="categ.selected" ng-options="c.name for c in categories">
        <option value="">No category</option>
    </select>
    

    Demo on Plunker


    categ.selected can be default set to null in your controller if needed:

    $scope.categ = {"selected": null};
    

    Update from comment:

    It seems you can't hard-code 2 options in a ng-options, so I suggest you to push the "No category" option in categories in your controller:

    $scope.categories.push({id:null, name:'No category', noCat:'true'});
    

    Note the noCat: 'true' that will be used to be not displayed on the first select.

    Now your HTML becomes:

    <select ng-model="person.category1" 
            ng-options="c.id as c.name for c in categories | filter: {noCat: '!true'}">
        <option value="" disabled>Select Category 1</option>
    </select>
    <select ng-model="person.category2" ng-options="c.id as c.name for c in categories">
        <option value="" disabled>Select Category 2</option>
    </select>
    

    New Plunker