为样式选择选项组

时间:2014-09-04 06:06:00

标签: angularjs ng-options

如何使用selectng-options选项组添加样式?

HTML:

<select ng-model="filteredBy" ng-options="obj_data.value as obj_data.title group by obj_data.group for obj_data in data"></select>

JS:

  $scope.filteredBy = 'true';
    $scope.data = [{
      "group": "byStatus",
      "title": "ACTIVE",
      "value": "false"
    }, {
      "group": "byStatus",
      "title": "COMPLETED",
      "value": "true"
    }, {
      "group": "byColor",
      "title": "Blue",
      "value": "#27a9e3"
    }, {
      "group": "byColor",
      "title": "Green",
      "value": "#28b779"
    }];

在上面的例子中,我想给颜色(蓝色和绿色)设置样式。

如何使用ng-options`?

DEMO PLUNKR

1 个答案:

答案 0 :(得分:7)

如果你想为选项赋予颜色,那么你必须使用ng-repeat而不是ng-option然后使用ng-style设置背景颜色......

<select ng-model="filteredBy">
  <option ng-repeat="val in data" ng-style = "{'background':val.value}" >{{val.title}}</option>     
</select>

对于分组你需要修改数据如下

JS

$scope.filteredBy = 'true';
$scope.data = [{
  'group': 'byStatus',
  'content':[{'title': 'ACTIVE','value': 'false'}, {'title': 'COMPLETED','value': 'true'
}]}, {
  'group': 'byColor',
  'content':[{'title': 'Blue','value': '#27a9e3'}, {'title': 'Green',
  'value': '#28b779'}]

}];

HTML

<select ng-model="filteredBy">
  <optgroup ng-repeat="val in data" label={{val.group}} >
    <option ng-repeat="v in val.content" ng-style = "{'background':v.value}" >{{v.title}}</option>
  </optgroup>
</select>