0
0

More than 5 years have passed since last update.

[Angular.js]背景色の濃さを変更するdirective

Posted at

使い道がいまいち伝わらなさそうだけど、ng-repeatとかで要素を並べるとき、要素の背景色の濃さを変更したいとか、背景色を動的に指定した色の範囲で変更したいとか。
あまりキレイに書けなかった。

gradation.js
app.directive('gradation', function() {
  return {
    scope: {
      gradation: "="
    },
    link: function(scope, element, attrs) {
      scope.$watch('gradation', function(gradation) {
        updateGradation(gradation);
      });

      var updateGradation = function(gradation) {
        var color = !isFinite(gradation) ? "#" + START.R.toString(16) + START.G.toString(16) + START.B.toString(16)
          : "#" + hex("R", gradation) + hex("G", gradation) + hex("B", gradation);
        angular.element(element[0]).css('background', color);
      };

      var hex = function(type, gradation) {
        var diff = END[type] - START[type];
        var color = START[type] + diff * gradation;
        return (~~color).toString(16);
      };

      var START = {
        R: 187, G: 223, B: 251
      };

      var END = {
        R: 25, G: 118, B: 210
      };
    }
  }
});

使い方

こんな感じ。gradationに0~1の値を設定する。実際には変数をバインドして「ng-repatで列挙した要素の重要度に応じて背景色を濃くする」ようなことをしている。

index.html
<ul>
  <li ng-repeat="item in items" gradation="0.5">
    <p>ほげ</p>
  </li>
</ul>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0