2013-08-27 50 views
1

我有,我想在下拉菜单中显示的对象列表,我使用NG选项做到这一点:角JS - 在NG选项更换空值

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

然而,一些我正在使用的对象的属性可能为空。在此示例中,颜色的阴影可能设置为空。

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

不是有下降的值下降是yellow null,我想它只是yellow

有没有办法用一个空字符串替换空值?我已经尝试过使用ngModel。$ parsers,但只有在选择特定选项后才会调用$ parser。是否有一段时间才会生成选项标签,以便我可以进行更换?

这里是一个包含了我执行$解析器

回答

2

一个filter会做的伎俩的jsfiddle。事情是这样的:

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

,然后你ng-options应该是这样的:

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

看到这个小提琴:http://jsfiddle.net/EBnPe/

0

这里有一个不同的方法可以尝试:

的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