msqar msqar - 5 months ago 33
Javascript Question

Add a background or not depending on angularjs condition using ng-style

I'm trying to add a background url style depending on a condition, so I attemped using data-ng-style but couldn't make it work for some reason, i don't know what I'm doing wrong.

data-ng-style="true : {'background-image': 'url(' + getThumbnailUrl(item) + ')'}, false : {}[item.thumbnailClass === undefined]"


Basically, what I want to do is, if thumbnailClass is undefined, set the background-image as data-ng-style, otherwise, do nothing.

Adding JSFiddle http://jsfiddle.net/Lvc0u55v/5666/
Imagine even that fafa is boolean, if true apply the style, if false, dont do anything.

How can I achieve this in AngularJS ? Thanks.

Answer

Your syntax is just a bit off. This should work.

data-ng-style="{'background-image': (item.thumbnailClass === undefined) ? 'url(' + getThumbnailUrl(item) + ')' : ''}"