2016-05-19 45 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

相關問題