If you need to bind only string values โโ(not to the object), you can easily achieve what you want by using the ngRepeat ed <option> elements (instead of 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>
If you use a small custom directive, you can implement it as follows:
app.directive('optionClassExpr', function ($compile, $parse) { var 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) { var optionsExp = attrs.ngOptions; if (!optionsExp) return; var match = optionsExp.match(NG_OPTIONS_REGEXP); if (!match) return; var values = match[7]; var classExpr = $parse(attrs.optionClassExpr); scope.$watchCollection(function () { return elem.children(); }, function (newValue) { angular.forEach(newValue, function (child) { var child = angular.element(child); var val = child.val(); if (val) { child.attr('ng-class', values + '[' + val + '].' + attrs.optionClassExpr); $compile(child)(scope); } }); }); } }; });
And use it as follows:
<select ng-model="someObj" ng-options="obj as obj.color for obj in objects" option-class-expr="color"> </select>
See also this updated short demo .
source share