Search code examples
cssangularjsng-class

Give a new class by ng-class with variable value


Hi I've got follow code:

angular.module("myApp", []).controller("myController", function($scope) {
  $scope.fieldSize = "cInputLarge"; //Change for the effect to -> cInputMedium, cInputLarge
});
.cDefault {
  width: 50px;
}
.cInputMedium {
  width: 100px;
}
.cInputLarge {
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myController">
  <input class="cDefault" ng-class="{{fieldSize}}">
  <br>
  <br>{{fieldSize}}
</div>

My goal is, to give to the input a class name, which changes the width of it. I know how ng-class works with conditions, but is something like this also possible (to give a class name in the ng-class and it takes it's properties)?

Thanks and cheers.


Solution

  • Just use the name of the variable, it should be sufficient:

    angular.module("myApp", []).controller("myController", function($scope) {
      $scope.fieldSize = "cInputLarge"; //Change for the effect to -> cInputMedium, cInputLarge
    });
    .cDefault {
      width: 50px;
    }
    .cInputMedium {
      width: 100px;
    }
    .cInputLarge {
      width: 200px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="myApp" ng-controller="myController">
      <input class="cDefault" ng-class="fieldSize">
      <br>
      <br>{{fieldSize}}
    </div>