AngularJSでCSSを設定してみる

AngularJSでCSSを設定してみる。

サンプルプログラム

<!DOCTYPE html>
<html lang="ja" ng-app>
<head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <style>
    .red   {color: #F00;}
    .green {color: #0F0;}
    .blue  {color: #00F;}
  </style>
</head>
<body>
  <p ng-style="x">Hello, world!<br />
  <button ng-click="x = {color: '#F00'}"></button>
  <button ng-click="x = {color: '#0F0'}"></button>
  <button ng-click="x = {color: '#00F'}"></button>
  <br />

  <p ng-style="{color: y}">Hello, world!<br />
  <button ng-click="y = '#F00'"></button>
  <button ng-click="y = '#0F0'"></button>
  <button ng-click="y = '#00F'"></button>
  <br />

  <p ng-class="z">Hello, world!<br />
  <button ng-click="z = 'red'  "></button>
  <button ng-click="z = 'green'"></button>
  <button ng-click="z = 'blue' "></button>
  <br />

  <p ng-class="{red:r, green:g, blue:b}">Hello, world!<br />
  <button ng-click="r = true;  g = false; b = false;"></button>
  <button ng-click="r = false; g = true;  b = false;"></button>
  <button ng-click="r = false; g = false; b = true; "></button>
  <br />
</body>
</html>

ボタンを押すとHello, worldの色が変わる。


以下、説明。

ng-style

ng-styleにはスタイルを指定できる。

<p ng-style="x">Hello, world!<br />
<button ng-click="x = {color: '#F00'}"></button>
<button ng-click="x = {color: '#0F0'}"></button>
<button ng-click="x = {color: '#00F'}"></button>

下記のようにスタイルの項目ごとに設定することもできる。

<p ng-style="{color: y}">Hello, world!<br />
<button ng-click="y = '#F00'"></button>
<button ng-click="y = '#0F0'"></button>
<button ng-click="y = '#00F'"></button>

ng-class

ng-classでは、クラス名を設定できる。

<p ng-class="z">Hello, world!<br />
<button ng-click="z = 'red'  "></button>
<button ng-click="z = 'green'"></button>
<button ng-click="z = 'blue' "></button>

下記のようにクラスを複数指定してON/OFFすることもできる。

<p ng-class="{red:r, green:g, blue:b}">Hello, world!<br />
<button ng-click="r = true;  g = false; b = false;"></button>
<button ng-click="r = false; g = true;  b = false;"></button>
<button ng-click="r = false; g = false; b = true; "></button>