LoginSignup
9
6

More than 5 years have passed since last update.

ng-classの使い方メモ

Posted at

普通の使いかた。
文字が赤と青の色で表示されます。

html
<html ng-app="App" ng-controller="AppCtrl">
<body>
  <div ng-class="{redColor:isRed}">赤く表示されます。</div>
  <div ng-class="{blueColor:isBlue}">青く表示されます。</div>
</body>
</html>
js
angular.module('App', [])
  .controller('AppCtrl', ['$scope', function($scope) {
    $scope.isRed = true;
    $scope.isBlue = true;
  }])
css
.redColor {
  color: red;
}
.blueColor {
  color: blue;
}

サンプル

class名をハイフンで区切った場合は、下記のように''で囲む必要があります。
あたりまえか・・・。

html
<html ng-app="App" ng-controller="AppCtrl">
<body>
  <div ng-class="{'red-color':isRed}">赤く表示されます。</div>
  <div ng-class="{'blue-Color':isBlue}">青く表示されます。</div>
</body>
</html>

下記のような書き方もできます。どんなメリットがあるのかがよくわかりませんでした。。。

html
<html ng-app="App" ng-controller="AppCtrl">
<body>
  <div ng-class="{true:'red-color'}[isRed]">赤く表示されます。</div>
  <div ng-class="{true:'blue-Color'}[isBlue]">青く表示されます。</div>
</body>
</html>

サンプル

9
6
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
9
6