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

I_Debug_Everything picture I_Debug_Everything · Mar 7, 2013 · Viewed 51.1k times · Source

I have an array of Person objects

var persons = [
{Name:'John',Eligible:true},
{Name:'Mark',Eligible:true},
{Name:'Sam',Eligible:false},
{Name:'Edward',Eligible:false},
{Name:'Michael',Eligible:true}
];

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 ng-class in select inorder to achieve this? Since we are not using any option tag it wont work if i simply add ng-class in the select element itself.

Answer

Ben Lesh picture Ben Lesh · Mar 7, 2013

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 (Nov 30 '13 at 3:17) 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) {
              angular.element(option).addClass(className);
            }
          });
        });
      });
    }
  };
});

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.