user3497581
user3497581

Reputation: 39

how to apply css class and also change css attribute dynamically in angularjs using ng-class?

I Want to apply a css class say 'headerStyle' but also change the color attribute defined in 'headerStyle' when the user choose a color from color picker like this. The catch is that I only want to use ng-class. Is it possible to be able to do it using only ng-class, I have done the same thing using mixture of class and ng-style but wish to do it using ng-class only.

HTML Code :

<input colorpicker type="text" ng-model="headerColor"> 

I tried like this but not working - Header Div :

<div ng-class="[headerStyle:true, {'background-color' : headerColor}]">

and also like this-

<div ng-class= "{headerStyle:true, 'background-color' : headerColor}">

Here is my css class headerStyle -

 .headerStyle {
       font-family: Helvetica, Arial, sans-serif !important;
       padding-top: 4px;
       font-size: 15px;
       color: #ffffff;
       text-align: center;
       text-shadow: #666666 1px 1px 1px;
       line-height: 16px;
       border: none;
  }

Thanx in Advance

Upvotes: 0

Views: 3754

Answers (1)

Okazari
Okazari

Reputation: 4597

<div class= "headerStyle" ng-class= "{'background-color' : headerColor}">

Should be enough. You don't need to put a static class into ng-class. ng-class will add the other classes to the static ones.

If headerColor evaluate to true. The result will be :

<div class= "headerStyle background-color">

EDIT :

According to your comment, your need is ng-style.

<div class= "headerStyle" ng-style="divStyle">

And in your js :

$scope.headerColor = "#FFFFFF";
$scope.divStyle = {
     background-color : $scope.headerColor
}

Some precision

ng-class :

ng-class is used to define class for an element according to some values. Its purpose is to add dynamic classes

ng-style :

ng-style is used to give a style object with some custom css. Its purpose is to add dynamic style

Here is a plunker with two working exemples

Upvotes: 1

Related Questions