从下拉列表中选择一种颜色,并在angularjs1中设置为背景

时间:2018-03-23 07:22:05

标签: angularjs

我希望程序从下拉列表中选择一种颜色并设置为背景颜色。我已经为它写了一个代码。我使用过指令 - 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 个答案:

答案 0 :(得分:0)

您可以尝试使用以下代码,也可以查看适用于您的示例方案的plunker链接

模板:

    <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>

控制器:

$scope.backgroundColors = [
    { name: "Red", hex: "#F21B1B" },
    { name: "Blue", hex: "#0099CC" }, 
    { name: "Green", hex: "#07BA16" },
    { name: "Yellow", hex: "#FFFF99"}];

答案 1 :(得分:0)

您需要做的就是更改您的P标签,如下所示

 <p ng-style="{background-color: '{{selectcolor.hex}}'}"></p>