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

标签 angularjs ng-options

我正在使用 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/

相关文章:

angularjs - angularjs 支持哪些版本的 Firefox?

javascript - Angular.js 说自定义 HTTP 响应 header 为空

angularjs - AngularJS 中的动态下拉选择不起作用

javascript - Angular js,在选择元素上我想发布数据以将其保存在数据库中,然后我想使用 PUT 更新它而不重新加载页面

android - nativescript-sqlite 和 angular2 模块未找到异常

javascript - AngularJS 指令 : "templateUrl" doesn't work while "template" works

javascript - 样式标签中的 Angular

javascript - AngularJS:为什么使用 ng-options 时 $element.find ('option' ) 返回一个空数组?

javascript - 如何过滤 select 元素的 ng-options 中的数据?

angularjs - 根据选择值过滤 angularjs 中的结果