webta.st.ic
webta.st.ic

Reputation: 5179

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.

Upvotes: 0

Views: 827

Answers (3)

Hadi
Hadi

Reputation: 17299

Or try this

   <input class="cDefault"  ng-class="{{'fieldSize'}}">

Upvotes: 0

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>

Upvotes: 1

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

Yes its correct . You can bind to a scope variable

Upvotes: 0

Related Questions