DJ Sprouse
DJ Sprouse

Reputation: 83

Angular JS - Replacing null values in ng-options

I have a list of objects that I want to display in a drop down menu and I am using ng-options to do it:

<select ng-model="query.color" ng-options="c.name + ' ' + c.shade for c in colors" />

However, some properties of the objects I am using may be null. In this example, the shade for a color may be set to null.

$scope.colors = [{
    name: 'black',
    shade: 'dark'
}, {
    name: 'yellow',
    shade: null
}];

Rather than have the value of the drop down be yellow null, I'd like it to just be yellow

Is there a way to replace the null value with an empty string? I have tried using ngModel.$parsers, but $parsers is only called once the specific option has been selected. Is there a moment before the option tags are generated where I can make the replacement?

Here is the jsfiddle that includes my implementation of $parsers

Upvotes: 2

Views: 2953

Answers (2)

Michael Benford
Michael Benford

Reputation: 14114

Here's a different approach you can try:

Javascript

function MyCtrl($scope) {
    function Color(name, shade) {
        this.name = name;
        this.shade = shade;
        this.displayName = name + ' ' + (shade || '');
    }
    $scope.colors = [
        new Color('black','dark'),
        new Color('yellow', null)
    ];    
    $scope.query = { color: $scope.colors[1] };
}

HTML

<div ng-controller="MyCtrl">
  <select ng-model="query.color" ng-options="c.displayName for c in colors">
  </select>
  <pre>
       Live: query={{query.color}}
  </pre>
</div>

jsFiddle here.

Upvotes: 0

dnc253
dnc253

Reputation: 40357

A filter would do the trick. Something like this:

myApp.filter('myFilter', function() {
    return function (c) {
        var text = c.name;
        if (null !== c.shade)
        {
            text += " " + c.shade;
        }
        return text;
    };
});

and then your ng-options would look like this:

ng-options="c | myFilter for c in colors"

See this fiddle: http://jsfiddle.net/EBnPe/

Upvotes: 2

Related Questions