ui-select: How to change background color of selected element?

I am using ui-select in combination with angularjs v1.5. Here is my html code:

<ui-select multiple sortable="true" ng-model="RealtimeCtrl.selectedPersons" theme="bootstrap">

<ui-select-match placeholder="Select or search a person in the list...">{{$item.username}}</ui-select-match>

<ui-select-choices repeat="item in RealtimeCtrl.people | filter: $select.search">
  <div ng-bind-html="item.username | highlight: $select.search"></div>
  <!--<small ng-bind-html="item.email | highlight: $select.search"></small>-->
</ui-select-choices>

</ui-select>

In angular I have a basic controller that fills the people variable with data. My question is pretty simple but I didn’t find anything similar asked before – how to give ui-select selected element a specific css background color?

I would store this randomly generated color in angular controller.

Any ideas? Any help would be much appreciated.

Answer

I solved this problem the ugly way, but it works. First I added a function call to ui-select element on select event (occurs when an item was selected):

<ui-select on-select="MyCtrl.onSelected($item);" on-remove="MyCtrl.onRemove($item);" multiple sortable="true" ng-model="MyCtrl.selectedPersons" theme="bootstrap">

<ui-select-match placeholder="Select or search a person in the list..."><span id="{{$item.$$hashKey}}">{{$item.username}}</span></ui-select-match>

<ui-select-choices repeat="item in MyCtrl.people | filter: $select.search">
  <div ng-bind-html="item.username | highlight: $select.search"></div>
  <!--<small ng-bind-html="item.email | highlight: $select.search"></small>-->
</ui-select-choices>

</ui-select>

I added a html id property on the span element with the value of {{$item.$$hashKey}}. The trick is I needed to change the background color of the parent of the selected span so I needed an id so that I could reference the proper parent. If there is a more elegant way to do this, please let me know.

Lastly, onSelected method is implemented in controller:

vm.onSelected = function(x) {
    document.getElementById(x.$$hashKey).parentElement.parentElement.style.backgroundColor = x.color;
};

This method changes the background color of the selected element parent. The color for each object is already stored in a object property.

When the user removes a certain element, a for loop runs over all selected persons and ensures that color of each DOM element stays the same as it was before the user removed a certain element.

vm.onRemove = function(x) {
    for (var i = 0; i < vm.selectedPersons.length; i++) {
        var x = vm.selectedPersons[i];
        document.getElementById(x.$$hashKey).parentElement.parentElement.style.backgroundColor = x.color;
    }
};