2016-05-19 47 views
1

我正在实施角度js中的颜色代码选择器,并尝试根据之前选择的值将颜色代码设置为焦点。 例如,如果保存的颜色是蓝色的,那么我必须在颜色选择器中将焦点设置为蓝色。未在颜色代码选择器中设置焦点

标记

<div class="tdata" ng-repeat="color in colors" 
    ng-class="{'selected':$index == selectedRow}" 
    ng-click="setClickedRow($index)" 
    style="background-color:{{color}};"> 
</div> 

控制器:

app.controller('myctrl', function($scope) { 
    $scope.colors = [ 
    '#36342a', 
    '#4f48d5', 
    '#03bbbb', 
    '#3eb308', 
    '#f0d817', 
    '#dd3333' 
    ]; 
    $scope.selectedRow = 0; // initialize our variable to null 
    $scope.setClickedRow = function(index) { //function that sets the value of selectedRow to current index 
    $scope.selectedRow = index; 
    } 
}); 

Plunker代码here

因为我已经硬编码选定的行为0.我将颜色以db的形式存储为十六进制。我想比较存储的颜色和颜色数组(我在范围中使用)并将颜色代码选择器中的焦点设置为。

回答

1

这是你在找什么

// Code goes here 
 

 
var app=angular.module('myApp',[]); 
 
app.controller('myctrl', function($scope){ 
 
$scope.colors = [ 
 
     '#36342a', 
 
     '#4f48d5', 
 
     '#03bbbb', 
 
     '#3eb308', 
 
     '#f0d817', 
 
     '#dd3333' 
 
     ]; 
 
     //color coming from db 
 
     $scope.dbColor = '#3eb308';//A color that exists in $scope.colors 
 
     //To get index of selected color 
 
     $scope.selectedRow = $scope.colors.indexOf($scope.dbColor); // initialize our variable to null 
 
     
 
     $scope.setClickedRow = function(index) 
 
    { //function that sets the value of selectedRow to current index 
 
    $scope.selectedRow = index; 
 
    } 
 
});
.tdata{width:25px;height:20px;border:1px solid #fff; 
 
    float:left 
 
} 
 
.selected { 
 
    background-image:none; 
 
    border: 5px solid #e1e1e1; 
 
}
<!DOCTYPE html> 
 
<html ng-app="myApp"> 
 

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

 
    <body ng-controller="myctrl"> 
 
    <h1>Hello Plunker!</h1> 
 

 
<div class="tdata" ng-repeat="color in colors" 
 
ng-class="{'selected':$index == selectedRow}" 
 
ng-click="setClickedRow($index)" 
 
style="background-color:{{color}};"> 
 
    </div> 
 

 

 

 
    </body> 
 

 
</html>

+0

这里选择行硬编码。我们如何找到这个价值 – RCM

+0

如果你不保存某处,你就找不到它!据我了解,预计你会从'DB'中选择颜色为十六进制,并且你有十六进制值的颜色列表。你确实比较了'DB'值与这些十六进制值之一,就是这样,所以你不需要选择颜色的索引。 – Bettimms

+0

是的,我想比较db值与数组 – RCM

相关问题