I_Debug_Everything I_Debug_Everything - 2 years ago 968
AngularJS Question

How to use ng-class in select with ng-options

I have an array of Person objects

var persons = [

and i am using select with ng-options like this:

<select ng-model="Blah" ng-options="person.Name for person in persons"></select>

I want to show the record with Eligible:false in red color.
So the problem is how do i use the
inorder to achieve this? Since we are not using any
tag it wont work if i simply add
in the
element itself.

Answer Source

You could create a directive that processed the options after the ngOptions directive is processed that updated them with the appropriate classes.

Update: The old code had a few bugs, and I've learned a bit since I answered this question. Here is a Plunk that was redone in 1.2.2 (but should work in 1.0.X as well)

Here is updated the Code:

app.directive('optionsClass', function ($parse) {
  return {
    require: 'select',
    link: function(scope, elem, attrs, ngSelect) {
      // get the source for the items array that populates the select.
      var optionsSourceStr = attrs.ngOptions.split(' ').pop(),
      // use $parse to get a function from the options-class attribute
      // that you can use to evaluate later.
          getOptionsClass = $parse(attrs.optionsClass);

      scope.$watch(optionsSourceStr, function(items) {
        // when the options source changes loop through its items.
        angular.forEach(items, function(item, index) {
          // evaluate against the item to get a mapping object for
          // for your classes.
          var classes = getOptionsClass(item),
          // also get the option you're going to need. This can be found
          // by looking for the option with the appropriate index in the
          // value attribute.
              option = elem.find('option[value=' + index + ']');

          // now loop through the key/value pairs in the mapping object
          // and apply the classes that evaluated to be truthy.
          angular.forEach(classes, function(add, className) {
            if(add) {

Here's how you'd use it in your markup:

<select ng-model="foo" ng-options="x.name for x in items" 
   options-class="{ 'is-eligible' : eligible, 'not-eligible': !eligible }"></select>

It works like ng-class does, with the exception that it's on a per-item-in-the-collection basis.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download