sooon
sooon

Reputation: 4878

Angular - dropdown menu background color

I have this code in html using Angular:

<select name="singleSelect" ng-model="priority.APME" style="width:100%;" ng-change="changedValue(priority.APME,$index,priority)" >
            <option value="" selected>Main Elements</option>
            <option ng-repeat="me in mainelements" value="{{$index}}" ng-disabled="me.optiondisable == true">{{me.Title}}</option>
          </select>

Now my client want to put different color for different options dynamically(option1 is green, option2 is red,...).

I googled and test with some code:

<option ng-repeat="me in main elements" style="background: #5456e3 !important;" value="{{$index}}" ng-disabled="me.optiondisable == true">{{me.Title}}</option>

and

<option ng-repeat="me in main elements" style="background-color: #5456e3 !important;" value="{{$index}}" ng-disabled="me.optiondisable == true">{{me.Title}}</option>

Both of the above not working. How can I achieve that?

Upvotes: 0

Views: 9755

Answers (2)

Raman Sahasi
Raman Sahasi

Reputation: 31841

There can be many ways, I would recommend that you specify a color attribute in the data itself and then set the background color according to that data.

see this Plunker I've created for the exact solution

angular.module('plunker', [])
.controller('MainCtrl', function ($scope) {
  $scope.fruits = [
    {name: 'Apple', color: '#5bb75b'},
    {name: 'Banana', color: '#08c'},
    {name: 'Cherry', color: 'yellow'},
  ];
  
  $scope.setBgColor = function() {
    $("#selectedFruit").css("background-color", JSON.parse($scope.selectedFruit).color);
  }
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="http://code.angularjs.org/1.0.7/angular.min.js" data-semver="1.0.7"></script>
    <script src="app.js"></script>
  </head>

<body ng-controller="MainCtrl">
  <select id="selectedFruit" ng-model="selectedFruit" style="background-color:{{JSON.parse($scope.selectedFruit).color}}" ng-change="setBgColor()">
    <option ng-repeat="sdata in fruits" style="background-color:{{sdata.color}}" value="{{sdata}}">{{sdata.name}}</option>
  </select>
</body>

</html>

Upvotes: 1

Sajal
Sajal

Reputation: 4401

You would have to assign a color property to incoming array, then use ng-style to bind that color to the option.

<select>
   <option value="" selected>Main Elements
   </option>
   <option ng-repeat="me in mainelements"
           ng-style ="{'background-color': me.Color}">{{me.Title}}
   </option>
</select>

Working Plunker

Upvotes: 3

Related Questions