color of option in Angular select

2.5k Views Asked by At

How do I assign a font colour for each option in the dropdown menu in angular?

I tried to do it by adding ng-style="{color:{{selectedCar.dropdown_color}};}" to the select tag, but it's not working.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.cars = {
        car01 : {brand : "Ford", model : "Mustang", dropdown_color : "red"},
        car02 : {brand : "Fiat", model : "500", dropdown_color : "green"},
        car03 : {brand : "Volvo", model : "XC90", dropdown_color : "blue"}
    }
});
</script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<p>Select a car:</p>

<select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars"
        ng-style="{color:{{selectedCar.dropdown_color}};">
</select>

<h1>You selected: {{selectedCar.brand}}</h1>
<h2>Model: {{selectedCar.model}}</h2>

</div>

</body>
</html>
1

There are 1 best solutions below

0
Julien On

The ngStyle directive take an AngularJS expression.

So you have to write ng-style="{color:selectedCar.dropdown_color}". But it will change the text color of all the options to be the one of the selected cars.

If you want to have each option in the color defined in the attribute dropdown_color, you will have to use ngRepeat instead and change your select from

<select ng-model="selectedOption" 
        ng-options="y.brand for (x, y) in cars" 
        ng-style="{color : selectedCar.dropdown_color}">
</select>

to be

<select ng-model="selectedCar" 
        ng-change="selectedCar = cars[selectedOption]" 
        ng-style="{color : selectedCar.dropdown_color}">
   <option ng-repeat="(key, value) in cars" 
           ng-style="{color: value.dropdown_color}" 
           ng-value="key" 
           ng-bind="value.brand"></option>
</select>