Tag Archives: css

Basic concept of using dynamic CSS class exchange by angular scope data

Here is simple example how to support changing CSS definition of HTML objects by using very simple classes which covers only limited parts of object and then making dynamic assignment this classes to object based on angular scope data.

To do this i prepared very simple css file:

.borderSolid{
  border-style:solid;
  }
  .borderDashed{
    border-style:dashed;
  }
.border1{
  border-width:1px;
}
.border2{
  border-width:2px;
}
.border3{
  border-width:3px;
}
.shadowYes{
  box-shadow:0 0 10px gray;
}
.shadowNo{
  box-shadow:none;
}
.borderSilver{
  border-color:silver;
}
.borderBlack{
  border-color:black;
}
.borderWhite{
  border-color:white;
}
.div{
  margin:20px;
  padding:20px;
  background-color:lightblue;
}

in this css definition you can find classes which defines border of div component. There are separated classes of border type (solid/dashed) border width (1,2 or 3px) border color(silver,black or white) and box shadow (yes,no)

Now i have an angular controller class where i have properties which defines also this values

function test($scope){
  $scope.borderColor="borderBlack";
  $scope.shadow="shadowYes";
  $scope.borderWidth="border1";
  $scope.borderType="borderSolid";
  };

Finally i have code where you can dynamically change which classes are active for each part of style and using binding capabilities of angularjs. All the magic is in this line:

<div class="div  {{shadow}} {{borderColor}} {{borderWidth}} {{borderType}}">

where i’m simply binding selected classes for each type.

Complete solution you can find here (example on plnkr.co):

Live a comment if you like this idea.