LoginSignup
4
7

More than 5 years have passed since last update.

複数ng-classを書く時の注意

Last updated at Posted at 2016-05-30

条件によってclassを使い分けるためにng-classを使用する際、
いくつかの条件によって振る舞いを変える場合の注意です。

piyoYellowが真の時はyellowクラスのみを適用、hogeRedの時はredクラスのみを適用させたい場合、以下のようにコードを書くとします。
(hogeRedの時はpiyoYelloの値に関わらずredクラスを適用させたい)

CSS

hogehoge.css
.yellow { color: yellow; }
.red    { color: red; }

Javascript

hogehoge.js
$scope.hogeRed = true;
$scope.piyoYellow = true;

HTML

index.html
<span ng-class="{yellow:piyoYellow, red:hogeRed}">ng-class テスト</span>

この時、「ng-class テスト」の文字は赤になります。
ですがそれは「piyoYellow」の後に書いた黄色が「hogeRed」されて赤色に上書きされたわけではなく、CSSの順番で赤色になっただけです。

そのため、 CSSの順番を

hogehoge.css
.red    { color: red; }
.yellow { color: yellow; }

とすると、文字色は黄色くなります。

この時、任意のclassのみを適用させたい場合は、ng-classの条件を修正する必要があります。

結論から先にいうと、HTMLを以下のコードのように修正します。

index.html
<span ng-class="{yellow:(piyoYellow && !hogeRed), red:hogeRed}">ng-class テスト</span>

ng-classの一つ目の式「yellow:(piyoYellow && !hogeRed)」で「hogeRed ではないとき」と条件を追加しました。

これで、CSSの順番に関わらず任意のclassのみを適用させることができます。

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