Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ng-style with condition

Tags:

angularjs

How can I apply style on some item in a list that satisfy listed condition:

        <div data-ng-repeat="item in items">
           <div data-ng-style="{'background' : 'red' : item.selected}> {{item.name}}
           <div> 
        <div> 

How is it possible to apply this style on item that is selected.

like image 482
mehmedju Avatar asked Aug 10 '15 10:08

mehmedju


People also ask

What is NgStyle in Angular?

NgStylelinkAn attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional . <unit> suffix (such as 'top.

Can we use NgClass and NgStyle together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

What is the difference between NgClass and NgStyle?

ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute. Following will be translated to class="deleted" when isDeleted variable is true.

Can we use two NgStyle in Angular?

With style binding we can set only a single style, however to set multiple styles we can use ngStyle directive.


2 Answers

Try this code,

  <div data-ng-repeat="item in items">
       <div data-ng-style="item.selected && {'background-color':'red'}"> 
           {{item.name}}
       <div> 
    <div>
like image 196
Shijin TR Avatar answered Sep 24 '22 10:09

Shijin TR


I think it would be best to use ng-class for your problem. You then make a new class for the red background, eg:

<style>
    .red-background{
        background-color: red;
    }
</style>

And then use this class according to the condition:

<div data-ng-class="{'red-background':item.selected}">{{item.name}}</div>

(don't forget the single quotes around the class name, they are easily overlooked)

like image 27
ndsmyter Avatar answered Sep 21 '22 10:09

ndsmyter