VKM VKM - 6 months ago 14
AngularJS Question

Focus not set in the color code picker

I am implementing the color code picker in angular js and tried to set the focus on color code based on the previously selected value.
For example if the saved color is blue then i have to set the focus on blue color in color picker.

Markup:

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


Controller:

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 code here.

In that i have hardcoded selected row as 0. I am storing color in db as hexadecimal. I want to compare the stored color with array of colors(which i used in scope) and set the focus in color code picker.

Answer

Is this what you are looking for

// 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="angular.js@1.0.x" 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>