我有一个想要在下拉菜单中显示的对象列表,我正在使用 ng-options 来执行此操作:
<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
有没有办法用空字符串替换 null 值?我尝试过使用 ngModel.$parsers,但 $parsers 仅在选择特定选项后才会被调用。在生成选项标签之前是否有一段时间我可以进行替换?
这是jsfiddle这包括我的 $parsers 实现
最佳答案
一个filter就可以了。像这样的事情:
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"
看到这个 fiddle :http://jsfiddle.net/EBnPe/
关于javascript - Angular JS - 替换 ng-options 中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18476767/