我正在使用 ng-options 作为选择下拉菜单。我想根据条件使用不同的颜色作为选项:
select(ng-model='myCompany', ng-options='company.code as company.name for company in companies' **if company.active -> text-color=green**)
可以这样做吗?
编辑(我的玉代码):
form(role='form', name='addForm', novalidate, rc-submit="add()")
.form-group
div.row
div.col-xs-12.col-md-3
select.form-control(ng-model='form.contract', ng-options='contract as contract.number for contract in contracts', options-class="{true:'active',false:'inactive'}[active]")
如果您只需要将选择绑定到字符串值(而不是对象),您可以通过使用轻松实现您想要的ngRepeat
ed <option>
元素(而不是ngOptions
):
<select ng-model="color">
<option value="">--- Select a color ---</option>
<option value="{{ c }}" style="background-color:{{ c }}" ng-repeat="c in colors">
{{ c }}
</option>
</select>
如果您需要一些自定义指令,您可以像这样实现它:
app.directive('optionClassExpr', function ($compile, $parse) {
const NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
return {
restrict: 'A',
link: function optionClassExprPostLink(scope, elem, attrs) {
const optionsExp = attrs.ngOptions;
if (!optionsExp) return;
const match = optionsExp.match(NG_OPTIONS_REGEXP);
if (!match) return;
const values = match[7];
const classExpr = $parse(attrs.optionClassExpr);
scope.$watchCollection(() => elem.children(), newValue => {
angular.forEach(newValue, child => {
const child = angular.element(child);
const val = child.val();
if (val) {
child.attr('ng-class', `${values}[${val}].${attrs.optionClassExpr}`);
$compile(child)(scope);
}
});
});
}
};
});
并像这样使用它:
<select
ng-model="someObj"
ng-options="obj as obj.color for obj in objects"
option-class-expr="color">
</select>
另请参阅此更新了简短的演示.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)