MrBuggy MrBuggy - 3 months ago 16
CSS Question

Set background-color for div when using ng-repeat

Hi I've got follow code:



angular.module("myApp", []).controller("myController", function($scope) {
$scope.boxList = [{
color: 'red'
}, {
color: '#F8F8F8'
}, {
color: 'rgb(50, 77, 32)'
}];
});

.box {
width: 15px;
height: 25px;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myController">
<div ng-repeat="box in boxList" class="box" ng-style="{'background-color': box.color}"></div>
</div>





I would like to loop the
boxList
with
ng-repeat
and set the
background-color
(text, hex or rgb) for my div box. So there should be three boxes with three different colors. I tried it with
ng-style
(saw some examples in stackoverflow) but it doesn't work. Whats wrong, any ideas? Thanks.

EDIT: SOLUTION ->
ng-style="{'background-color': box.color}


background-color
has to be within ' '.

Answer

here you go:

angular.module("myApp", []).controller("myController", function($scope) {
  $scope.boxList = [{
    color: 'red'
  }, {
    color: '#F8F8F8'
  }, {
    color: 'rgb(50, 77, 32)'
  }];
});
.box {
  width: 15px;
  height: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myController">
  <div ng-repeat="box in boxList" class="box" ng-style="{'background-color':'{{box.color}}'}"></div>
</div>

you're syntax was off, you missed some quotes and should have used interpolation ({{variable}}) in order to render the value.

this is the only thing I changed: ng-style="{'background-color':'{{box.color}}'}" so you can see the difference. Good luck ;)