skip to Main Content

I want the program to select a color from the dropdown list and set as background color. I have written a code for it. I have used directives – ng-model, ng-style,ng-repeat.

<html ng-app="Swabhav.Color">
<head>
    <title>Color-pick</title>
    <script src="angular.js"></script>
    <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-
 bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css"
/>
<script 
src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js">
 </script>


  </head>
  <body>
        <script>
                 var app = angular.module("Swabhav.Color", []); 
                 app.controller("dropdowncolor", ["$scope",function($scope) 
             {
                 $scope.colors = [{ name: "Red", hex: "#F21B1B" },
                                     { name: "Blue", hex: "#0099CC" }, 
                                     { name: "Green", hex: "#07BA16" },
                                     { name: "Yellow", hex: "#FFFF99"}];

                 }]);

                </script>

        <div ng-controller="dropdowncolor">
            <p>Select a color</p>

            <select ng-model="selectedcolor">
            <option ng-repeat="selectcolor in colors"  value="{{selectcolor.hex}}">
            your selected color is : {{selectcolor.name}}  
            <p ng-style="{'background-color':selectcolor.hex}"  ></p>
            </option>   

            </select>
            </div>

  </body>
 </html>

2

Answers


  1. You can try like the below code, also check this working plunker link for your example scenario,

    Templates:

        <select ng-model="selectedcolor" ng-options="color.name as color.name for color in backgroundColors">
        </select>
        <p ng-style="{'background-color': selectedcolor}">
          <br/>
          Your selected color is : {{selectedcolor}}  
          <br/><br/>
        </p>
    

    Controller:

    $scope.backgroundColors = [
        { name: "Red", hex: "#F21B1B" },
        { name: "Blue", hex: "#0099CC" }, 
        { name: "Green", hex: "#07BA16" },
        { name: "Yellow", hex: "#FFFF99"}];
    
    Login or Signup to reply.
  2. All you need to do is change your P tag like below

     <p ng-style="{background-color: '{{selectcolor.hex}}'}"></p>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search