Marcus
Marcus

Reputation: 81

Angularjs array as style array

I have a little problem with a object array in AngularJS. I need to create an array with fixed lenght that contains object like this:

var obj = {
"background-color" : "FFFF"
}

Now I can achieve this result easily in javascript and I have created an array inside the angularjs controller

$scope.selected_colors = [];
for(var i = 0; i < 20; i++){
$scope.selected_colors.push(getRandomColor());
}

where getRandomColor() is a function that select a random color from a list. At this point in my web page I have a piece of code that renders a list of objects (I want each of them having a different background color):

<div class='card' ng-repeat='item in items'>
<div class='background' ng-style='selected_colors[$index]'>
...
</div>
</div>

But at this point no background is rendered. But if I create an object like that:

$scope.background = {
"background-color": "blue"
}

and if I use that in ng-style call I see the background. Is a problem with runtime generated objects? I'm missing something that makes this model work? Is there a better way to achieve this result in angularjs?

Upvotes: 0

Views: 48

Answers (2)

Marcus
Marcus

Reputation: 81

Found the solution, was an error in declaring the color for a missing # in front of the hexadecimal code that was missing in building the color code string. I left the question up if someone needs a hint to perform the same operation in the future.

Thank you all.

Upvotes: 0

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

It looks like your getRandomColor() just return a color string (eg: blue), that make selected_colors[$index] is a color string but ng-style expect an object so your code doesn't work. To fix this, you just need to change your code to:

...
$scope.selected_colors.push({"background-color": getRandomColor()});
...

Upvotes: 1

Related Questions