gpt4 book ai didi

angularjs - 自定义 ng-options 选择外观

转载 作者:行者123 更新时间:2023-12-02 18:21:55 26 4
gpt4 key购买 nike

我正在使用 ng-options 作为选择下拉菜单。我想根据条件对选项使用不同的颜色:

select(ng-model='myCompany', ng-options='company.code as company.name for company in companies' **if company.active -> text-color=green**)

可以这样做吗?

编辑(我的 Jade 代码):

 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]")

最佳答案

如果您只需要将 select 绑定(bind)到字符串值(而不是对象),则可以使用 ngRepeat 轻松实现您想要的效果。编<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>
<小时/>

另请参阅此 updated short demo

关于angularjs - 自定义 ng-options 选择外观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24631325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com