1

I'm trying to set a css property depending on a scope variable.

Basically, something like this :

 <div ng-style="background: filters.area ? #f39c12 : #424242">

Or maybe it should be more like :

<div ng-style="filters.area ? 'background:#f39c12' : 'background:#424242'">

or even :

<div ng-style="{{filters.area ? 'background:#424242' : 'background:#ff0000'}}">

But none of the above worked

4 Answers 4

1

background value would be set by ternary operator & Also use { & } instead of {{}} interpolation.

Basically ng-style directive asks for JSON & internally it use element.css(JSON)

<div ng-style="{'background' : filters.area ? '#424242' : '#ff0000'}">
Sign up to request clarification or add additional context in comments.

2 Comments

I guess you meant without the first background since it already is in the ternary result. I have something like this : <div class="filterContent" ng-style="{filters.area ? 'background:#f39c12' : 'background:#ff0000'}"> but it doesn't do anything, the background of the filterContent class stays even if I add !important; after both color codes
@Ellone that was my bad in copy paste..do look at my updated answer
1

You have some syntax error in the expression inside ng-style directive. Try this way,

HTML :

<div ng-controller="MainController">
    <div id="customControl" ng-style="filterarea ? {'background': '#f39c12'} : {'background':'#424242'}"></div>
</div>

javaScript : (angularjs)

angular.module("myapp", []).controller("MainController", ["$scope", function($scope){
    $scope.filterarea = false;
}]);

CSS :

#customControl{
    width : 100px;
    height : 100px;
    background-color : yellow;
}

jsFiddle

1 Comment

Thanks ! ng-style="filters.area ? {'background': '#f39c12'} : {'background':'#424242'}"> works just fine !
0

You need to have a single pair '{}'. This code can be easily fixed by using

<div ng-style="{filters.area ? 'background:#424242' : 'background:#ff0000'}">

Comments

0

Fiddle: http://jsfiddle.net/jpk547zp/3/

For further help with ng-style check: https://docs.angularjs.org/api/ng/directive/ngStyle

<div ng-app="approvalApp">
    <div ng-controller="SimpleApprovalController" >
        <div ng-style="filters.area ? {'background-color' : '#424242'} : {'background-color' : '#ff0000'}">
            test data
        </div>
    </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.