How do I conditionally apply CSS styles in AngularJS?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







303















Q1. Suppose I want to alter the look of each "item" that a user marks for deletion before the main "delete" button is pressed. (This immediate visual feedback should eliminate the need for the proverbial "are you sure?" dialog box.) The user will check checkboxes to indicate which items should be deleted. If a checkbox is unchecked, that item should revert back to its normal look.



What's the best way to apply or remove the CSS styling?



Q2. Suppose I want to allow each user to personalize how my site is presented. E.g., select from a fixed set of font sizes, allow user-definable foreground and background colors, etc.



What's the best way to apply the CSS styling the user selects/inputs?










share|improve this question























  • useful article tech-blog.maddyzone.com/javascript/…

    – Rituraj ratan
    Sep 17 '14 at 12:34


















303















Q1. Suppose I want to alter the look of each "item" that a user marks for deletion before the main "delete" button is pressed. (This immediate visual feedback should eliminate the need for the proverbial "are you sure?" dialog box.) The user will check checkboxes to indicate which items should be deleted. If a checkbox is unchecked, that item should revert back to its normal look.



What's the best way to apply or remove the CSS styling?



Q2. Suppose I want to allow each user to personalize how my site is presented. E.g., select from a fixed set of font sizes, allow user-definable foreground and background colors, etc.



What's the best way to apply the CSS styling the user selects/inputs?










share|improve this question























  • useful article tech-blog.maddyzone.com/javascript/…

    – Rituraj ratan
    Sep 17 '14 at 12:34














303












303








303


155






Q1. Suppose I want to alter the look of each "item" that a user marks for deletion before the main "delete" button is pressed. (This immediate visual feedback should eliminate the need for the proverbial "are you sure?" dialog box.) The user will check checkboxes to indicate which items should be deleted. If a checkbox is unchecked, that item should revert back to its normal look.



What's the best way to apply or remove the CSS styling?



Q2. Suppose I want to allow each user to personalize how my site is presented. E.g., select from a fixed set of font sizes, allow user-definable foreground and background colors, etc.



What's the best way to apply the CSS styling the user selects/inputs?










share|improve this question














Q1. Suppose I want to alter the look of each "item" that a user marks for deletion before the main "delete" button is pressed. (This immediate visual feedback should eliminate the need for the proverbial "are you sure?" dialog box.) The user will check checkboxes to indicate which items should be deleted. If a checkbox is unchecked, that item should revert back to its normal look.



What's the best way to apply or remove the CSS styling?



Q2. Suppose I want to allow each user to personalize how my site is presented. E.g., select from a fixed set of font sizes, allow user-definable foreground and background colors, etc.



What's the best way to apply the CSS styling the user selects/inputs?







css angularjs






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 11 '12 at 3:39









Mark RajcokMark Rajcok

297k92438462




297k92438462













  • useful article tech-blog.maddyzone.com/javascript/…

    – Rituraj ratan
    Sep 17 '14 at 12:34



















  • useful article tech-blog.maddyzone.com/javascript/…

    – Rituraj ratan
    Sep 17 '14 at 12:34

















useful article tech-blog.maddyzone.com/javascript/…

– Rituraj ratan
Sep 17 '14 at 12:34





useful article tech-blog.maddyzone.com/javascript/…

– Rituraj ratan
Sep 17 '14 at 12:34












14 Answers
14






active

oldest

votes


















476














Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:





  • ng-class - use when the set of CSS styles is static/known ahead of time


  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.


  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)


  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)


  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)


  • ng-disabled and ng-readonly - use to restrict form element behavior


  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations


The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.



When the user changes the UI, Angular will automatically update the associated elements on the page.






Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.

ng-class accepts an "expression" that must evaluate to one of the following:




  1. a string of space-delimited class names

  2. an array of class names

  3. a map/object of class names to boolean values


Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:



<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
... HTML to display the item ...
<input type="checkbox" ng-model="item.checked">
</div>


Above, we used ng-class expression type #3 - a map/object of class names to boolean values.






Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.

ng-style accepts an "expression" that must evaluate to:




  1. an map/object of CSS style names to CSS values


For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):



<div class="main-body" ng-style="{color: myColor}">
...
<input type="text" ng-model="myColor" placeholder="enter a color name">





Fiddle for both of the above.

The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.






share|improve this answer


























  • This answer is terrific! Would you be willing to show me via jsfiddle what the difference would be if the click event was changing/adding a class on an area that wasn't the clicked element? Say a div elsewhere on the page.

    – tehaaron
    Oct 10 '13 at 21:47











  • it is useful article tech-blog.maddyzone.com/javascript/…

    – Rituraj ratan
    Sep 17 '14 at 12:34











  • Great anwser. Btw, have you ever tried applying angular filter to ng-style ?

    – Evi Song
    Jul 3 '15 at 8:12











  • I suggest adding an additional option related to Q2 that I just added in my recent answer to this question.

    – Gavin Palmer
    Nov 7 '15 at 14:30



















105














I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>). It seems that when you inspect the element with Developer Tools, the element.style has no style assigned. So instead of using ng-class, I have tried using ng-style, and in this case, the new CSS attribute does appear inside element.style. This code works great for me:



<tr ng-repeat="element in collection">

[...amazing code...]

<td ng-style="myvar === 0 && {'background-color': 'red'} ||
myvar === 1 && {'background-color': 'green'} ||
myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>

[...more amazing code...]

</tr>


Myvar is what I am evaluating, and in each case I apply a style to each <td> depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.



UPDATE



If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:



<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">


Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a OR we are in route_b, the active class will be applied.



This works just having a logic function on the right that returns true or false.



So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.



By the way, I forgot to give you the function isActive():



$rootScope.isActive = function(viewLocation) {
return viewLocation === $location.path();
};


NEW UPDATE



Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div, you can use the following code (very useful in ng-repeat):



<i class="fa" ng-class="{ 'fa-github'   : type === 0,
'fa-linkedin' : type === 1,
'fa-skype' : type === 2,
'fa-google' : type === 3 }"></i>



Icons from Font Awesome







share|improve this answer


























  • what a strange syntax, && should mean AND, like in any other c inspired language

    – Pizzaiola Gorgonzola
    Mar 18 '14 at 23:16






  • 3





    @PizzaiolaGorgonzola && does mean AND and || does mean OR. It's a clever hack using the short-circuit logic almost as a case/switch statement...

    – Stein G. Strindhaug
    Apr 1 '14 at 14:25











  • Thanks mit. I didn't realized of that detail.

    – Timbergus
    Nov 1 '15 at 13:37











  • The new update section worked like a charm! +1 for it!

    – Matias
    Jul 12 '16 at 18:36











  • used the example of ng-class as mentioned in New Update, worked pretty well for me. Pretty sleek

    – Acewin
    Feb 16 '17 at 18:07



















34














This works well when ng-class can't be used (for example when styling SVG):



ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"


(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)



I have published an article on working with AngularJS+SVG. It talks about this issue and numerous others. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS






share|improve this answer


























  • I don't see any mention of ng-attr in the 1.1.4 docs -- do you have a link?

    – Mark Rajcok
    May 21 '13 at 17:28











  • Sorry don't have a link. I found out about it by following the Angular forums, although I can't remember the exact page sorry.

    – Ashley Davis
    Jun 10 '13 at 3:59






  • 1





    The latest docs (v1.2) describe ng-attr- on the directives page, section ngAttr attribute bindings.

    – Mark Rajcok
    Aug 21 '13 at 12:50











  • With 1.2, this becomes a great answer. ng-class doesn't let you perform logic, but ng-attr-class does. They both have their uses, but I can bet a lot of developers will be looking for ng-attr-class.

    – Hylianpuffball
    Jan 6 '14 at 21:32











  • I got this to work well when other solutions provided here failed. Thank you.

    – dps
    Feb 21 '18 at 6:41



















12














span class="circle circle-{{selectcss(document.Extension)}}">


and code



$scope.selectcss = function (data) {
if (data == '.pdf')
return 'circle circle-pdf';
else
return 'circle circle-small';
};


css



.circle-pdf {
width: 24px;
height: 24px;
font-size: 16px;
font-weight: 700;
padding-top: 3px;
-webkit-border-radius: 12px;
-moz-border-radius: 12px;
border-radius: 12px;
background-image: url(images/pdf_icon32.png);
}





share|improve this answer


























  • Always avoid the iF word

    – LastTribunal
    Jul 27 '15 at 22:56











  • @LastTribunal why?

    – iamserious
    Aug 17 '15 at 10:55











  • I want to encourage to avoid directly using the class-attribute. This will overwrite changes made by other plugins on this element.

    – SimonSimCity
    Jun 21 '17 at 13:26



















10














This solution did the trick for me



<a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>





share|improve this answer































    7














    Another option when you need a simple css style of one or two properties:



    View:



    <tr ng-repeat="element in collection">
    [...amazing code...]
    <td ng-style="{'background-color': getTrColor(element.myvar)}">
    {{ element.myvar }}
    </td>
    [...more amazing code...]
    </tr>


    Controller:



    $scope.getTrColor = function (colorIndex) {
    switch(colorIndex){
    case 0: return 'red';
    case 1: return 'green';
    default: return 'yellow';
    }
    };





    share|improve this answer

































      7














      You can use ternary expression. There are two ways to do this:



      <div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>


      or...



      <div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>





      share|improve this answer





















      • 1





        Maybe u will find it better: <div ng-style="{ 'color': (myVariable > 100)? 'red' : 'blue' }"></div>

        – Dudi
        Mar 3 '18 at 7:19











      • Dudi, if not better, just as useful, so I added it to @maykel's "ternary expression" answer. Thanks to both of you!

        – jbobbins
        May 19 '18 at 6:43





















      6














      See the following example



      <!DOCTYPE html>
      <html ng-app>
      <head>
      <title>Demo Changing CSS Classes Conditionally with Angular</title>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
      <script src="res/js/controllers.js"></script>

      <style>

      .checkboxList {
      border:1px solid #000;
      background-color:#fff;
      color:#000;
      width:300px;
      height: 100px;
      overflow-y: scroll;
      }

      .uncheckedClass {
      background-color:#eeeeee;
      color:black;
      }
      .checkedClass {
      background-color:#3ab44a;
      color:white;
      }
      </style>

      </head>
      <body ng-controller="TeamListCtrl">
      <b>Teams</b>
      <div id="teamCheckboxList" class="checkboxList">

      <div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">

      <label>
      <input type="checkbox" ng-model="team.isChecked" />
      <span>{{team.name}}</span>
      </label>
      </div>
      </div>
      </body>
      </html>





      share|improve this answer































        2














        As of AngularJS v1.2.0rc, ng-class and even ng-attr-class fail with SVG elements (They did work earlier, even with normal binding inside the class attribute)



        Specifically, none of these work now:



        ng-class="current==this_element?'active':' ' "
        ng-attr-class="{{current==this_element?'active':' '}}"
        class="class1 class2 .... {{current==this_element?'active':''}}"


        As a workaround, I've to use



        ng-attr-otherAttr="{{current==this_element?'active':''}}"


        and then style using



        [otherAttr='active'] {
        ... styles ...
        }





        share|improve this answer































          1














          One more (in the future) way to conditionally apply style is by conditionally creating scoped style



          <style scoped type="text/css" ng-if="...">

          </style>


          But nowadays only FireFox supports scoped styles.






          share|improve this answer































            1














            There is one more option that I recently discovered that some people may find useful because it allows you to change a CSS rule within a style element - thus avoiding the need for repeated use of an angular directive such as ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.



            This option makes use of a service with service variables which are set by a controller and watched by an attribute-directive I call "custom-style". This strategy could be used in many different ways, and I attempted to provide some general guidance with this fiddle.



            var app = angular.module('myApp', ['ui.bootstrap']);
            app.service('MainService', function(){
            var vm = this;
            });
            app.controller('MainCtrl', function(MainService){
            var vm = this;
            vm.ms = MainService;
            });
            app.directive('customStyle', function(MainService){
            return {
            restrict : 'A',
            link : function(scope, element, attr){
            var style = angular.element('<style></style>');
            element.append(style);
            scope.$watch(function(){ return MainService.theme; },
            function(){
            var css = '';
            angular.forEach(MainService.theme, function(selector, key){
            angular.forEach(MainService.theme[key], function(val, k){
            css += key + ' { '+k+' : '+val+'} ';
            });
            });
            style.html(css);
            }, true);
            }
            };
            });





            share|improve this answer































              1














              well i would suggest you to check condition in your controller with a function returning true or false .



              <div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>


              and in your controller check the condition



              $scope.getTodayForHighLight = function(today, date){
              return (today == date);
              }





              share|improve this answer

































                0














                One thing to watch is - if the CSS style has dashes - you must remove them. So if you want to set background-color, the correct way is:



                ng-style="{backgroundColor:myColor}" 





                share|improve this answer





















                • 5





                  No, you don't have to. ng-style="{'background-color':myColor}" works perfectly well.

                  – gerasalus
                  Jul 7 '14 at 10:26



















                0














                Here's how i conditionally applied gray text style on a disabled button



                import { Component } from '@angular/core';

                @Component({
                selector: 'my-app',
                styleUrls: [ './app.component.css' ],
                template: `
                <button
                (click)='buttonClick1()'
                [disabled] = "btnDisabled"
                [ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}">
                {{btnText}}
                </button>`
                })
                export class AppComponent {
                name = 'Angular';
                btnText = 'Click me';
                btnDisabled = false;
                buttonClick1() {
                this.btnDisabled = true;
                this.btnText = 'you clicked me';
                setTimeout(() => {
                this.btnText = 'click me again';
                this.btnDisabled = false
                }, 5000);
                }
                }


                Here's a working example:
                https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html






                share|improve this answer






















                  protected by Pankaj Parkar Jun 10 '15 at 17:14



                  Thank you for your interest in this question.
                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                  Would you like to answer one of these unanswered questions instead?














                  14 Answers
                  14






                  active

                  oldest

                  votes








                  14 Answers
                  14






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  476














                  Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:





                  • ng-class - use when the set of CSS styles is static/known ahead of time


                  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.


                  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)


                  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)


                  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)


                  • ng-disabled and ng-readonly - use to restrict form element behavior


                  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations


                  The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.



                  When the user changes the UI, Angular will automatically update the associated elements on the page.






                  Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.

                  ng-class accepts an "expression" that must evaluate to one of the following:




                  1. a string of space-delimited class names

                  2. an array of class names

                  3. a map/object of class names to boolean values


                  Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:



                  <div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
                  ... HTML to display the item ...
                  <input type="checkbox" ng-model="item.checked">
                  </div>


                  Above, we used ng-class expression type #3 - a map/object of class names to boolean values.






                  Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.

                  ng-style accepts an "expression" that must evaluate to:




                  1. an map/object of CSS style names to CSS values


                  For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):



                  <div class="main-body" ng-style="{color: myColor}">
                  ...
                  <input type="text" ng-model="myColor" placeholder="enter a color name">





                  Fiddle for both of the above.

                  The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.






                  share|improve this answer


























                  • This answer is terrific! Would you be willing to show me via jsfiddle what the difference would be if the click event was changing/adding a class on an area that wasn't the clicked element? Say a div elsewhere on the page.

                    – tehaaron
                    Oct 10 '13 at 21:47











                  • it is useful article tech-blog.maddyzone.com/javascript/…

                    – Rituraj ratan
                    Sep 17 '14 at 12:34











                  • Great anwser. Btw, have you ever tried applying angular filter to ng-style ?

                    – Evi Song
                    Jul 3 '15 at 8:12











                  • I suggest adding an additional option related to Q2 that I just added in my recent answer to this question.

                    – Gavin Palmer
                    Nov 7 '15 at 14:30
















                  476














                  Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:





                  • ng-class - use when the set of CSS styles is static/known ahead of time


                  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.


                  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)


                  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)


                  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)


                  • ng-disabled and ng-readonly - use to restrict form element behavior


                  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations


                  The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.



                  When the user changes the UI, Angular will automatically update the associated elements on the page.






                  Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.

                  ng-class accepts an "expression" that must evaluate to one of the following:




                  1. a string of space-delimited class names

                  2. an array of class names

                  3. a map/object of class names to boolean values


                  Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:



                  <div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
                  ... HTML to display the item ...
                  <input type="checkbox" ng-model="item.checked">
                  </div>


                  Above, we used ng-class expression type #3 - a map/object of class names to boolean values.






                  Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.

                  ng-style accepts an "expression" that must evaluate to:




                  1. an map/object of CSS style names to CSS values


                  For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):



                  <div class="main-body" ng-style="{color: myColor}">
                  ...
                  <input type="text" ng-model="myColor" placeholder="enter a color name">





                  Fiddle for both of the above.

                  The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.






                  share|improve this answer


























                  • This answer is terrific! Would you be willing to show me via jsfiddle what the difference would be if the click event was changing/adding a class on an area that wasn't the clicked element? Say a div elsewhere on the page.

                    – tehaaron
                    Oct 10 '13 at 21:47











                  • it is useful article tech-blog.maddyzone.com/javascript/…

                    – Rituraj ratan
                    Sep 17 '14 at 12:34











                  • Great anwser. Btw, have you ever tried applying angular filter to ng-style ?

                    – Evi Song
                    Jul 3 '15 at 8:12











                  • I suggest adding an additional option related to Q2 that I just added in my recent answer to this question.

                    – Gavin Palmer
                    Nov 7 '15 at 14:30














                  476












                  476








                  476







                  Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:





                  • ng-class - use when the set of CSS styles is static/known ahead of time


                  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.


                  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)


                  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)


                  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)


                  • ng-disabled and ng-readonly - use to restrict form element behavior


                  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations


                  The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.



                  When the user changes the UI, Angular will automatically update the associated elements on the page.






                  Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.

                  ng-class accepts an "expression" that must evaluate to one of the following:




                  1. a string of space-delimited class names

                  2. an array of class names

                  3. a map/object of class names to boolean values


                  Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:



                  <div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
                  ... HTML to display the item ...
                  <input type="checkbox" ng-model="item.checked">
                  </div>


                  Above, we used ng-class expression type #3 - a map/object of class names to boolean values.






                  Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.

                  ng-style accepts an "expression" that must evaluate to:




                  1. an map/object of CSS style names to CSS values


                  For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):



                  <div class="main-body" ng-style="{color: myColor}">
                  ...
                  <input type="text" ng-model="myColor" placeholder="enter a color name">





                  Fiddle for both of the above.

                  The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.






                  share|improve this answer















                  Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:





                  • ng-class - use when the set of CSS styles is static/known ahead of time


                  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.


                  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)


                  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)


                  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)


                  • ng-disabled and ng-readonly - use to restrict form element behavior


                  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations


                  The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.



                  When the user changes the UI, Angular will automatically update the associated elements on the page.






                  Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.

                  ng-class accepts an "expression" that must evaluate to one of the following:




                  1. a string of space-delimited class names

                  2. an array of class names

                  3. a map/object of class names to boolean values


                  Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:



                  <div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
                  ... HTML to display the item ...
                  <input type="checkbox" ng-model="item.checked">
                  </div>


                  Above, we used ng-class expression type #3 - a map/object of class names to boolean values.






                  Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.

                  ng-style accepts an "expression" that must evaluate to:




                  1. an map/object of CSS style names to CSS values


                  For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):



                  <div class="main-body" ng-style="{color: myColor}">
                  ...
                  <input type="text" ng-model="myColor" placeholder="enter a color name">





                  Fiddle for both of the above.

                  The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Feb 8 at 15:14









                  Jimenemex

                  2,1071525




                  2,1071525










                  answered Dec 11 '12 at 3:39









                  Mark RajcokMark Rajcok

                  297k92438462




                  297k92438462













                  • This answer is terrific! Would you be willing to show me via jsfiddle what the difference would be if the click event was changing/adding a class on an area that wasn't the clicked element? Say a div elsewhere on the page.

                    – tehaaron
                    Oct 10 '13 at 21:47











                  • it is useful article tech-blog.maddyzone.com/javascript/…

                    – Rituraj ratan
                    Sep 17 '14 at 12:34











                  • Great anwser. Btw, have you ever tried applying angular filter to ng-style ?

                    – Evi Song
                    Jul 3 '15 at 8:12











                  • I suggest adding an additional option related to Q2 that I just added in my recent answer to this question.

                    – Gavin Palmer
                    Nov 7 '15 at 14:30



















                  • This answer is terrific! Would you be willing to show me via jsfiddle what the difference would be if the click event was changing/adding a class on an area that wasn't the clicked element? Say a div elsewhere on the page.

                    – tehaaron
                    Oct 10 '13 at 21:47











                  • it is useful article tech-blog.maddyzone.com/javascript/…

                    – Rituraj ratan
                    Sep 17 '14 at 12:34











                  • Great anwser. Btw, have you ever tried applying angular filter to ng-style ?

                    – Evi Song
                    Jul 3 '15 at 8:12











                  • I suggest adding an additional option related to Q2 that I just added in my recent answer to this question.

                    – Gavin Palmer
                    Nov 7 '15 at 14:30

















                  This answer is terrific! Would you be willing to show me via jsfiddle what the difference would be if the click event was changing/adding a class on an area that wasn't the clicked element? Say a div elsewhere on the page.

                  – tehaaron
                  Oct 10 '13 at 21:47





                  This answer is terrific! Would you be willing to show me via jsfiddle what the difference would be if the click event was changing/adding a class on an area that wasn't the clicked element? Say a div elsewhere on the page.

                  – tehaaron
                  Oct 10 '13 at 21:47













                  it is useful article tech-blog.maddyzone.com/javascript/…

                  – Rituraj ratan
                  Sep 17 '14 at 12:34





                  it is useful article tech-blog.maddyzone.com/javascript/…

                  – Rituraj ratan
                  Sep 17 '14 at 12:34













                  Great anwser. Btw, have you ever tried applying angular filter to ng-style ?

                  – Evi Song
                  Jul 3 '15 at 8:12





                  Great anwser. Btw, have you ever tried applying angular filter to ng-style ?

                  – Evi Song
                  Jul 3 '15 at 8:12













                  I suggest adding an additional option related to Q2 that I just added in my recent answer to this question.

                  – Gavin Palmer
                  Nov 7 '15 at 14:30





                  I suggest adding an additional option related to Q2 that I just added in my recent answer to this question.

                  – Gavin Palmer
                  Nov 7 '15 at 14:30













                  105














                  I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>). It seems that when you inspect the element with Developer Tools, the element.style has no style assigned. So instead of using ng-class, I have tried using ng-style, and in this case, the new CSS attribute does appear inside element.style. This code works great for me:



                  <tr ng-repeat="element in collection">

                  [...amazing code...]

                  <td ng-style="myvar === 0 && {'background-color': 'red'} ||
                  myvar === 1 && {'background-color': 'green'} ||
                  myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>

                  [...more amazing code...]

                  </tr>


                  Myvar is what I am evaluating, and in each case I apply a style to each <td> depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.



                  UPDATE



                  If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:



                  <li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">


                  Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a OR we are in route_b, the active class will be applied.



                  This works just having a logic function on the right that returns true or false.



                  So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.



                  By the way, I forgot to give you the function isActive():



                  $rootScope.isActive = function(viewLocation) {
                  return viewLocation === $location.path();
                  };


                  NEW UPDATE



                  Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div, you can use the following code (very useful in ng-repeat):



                  <i class="fa" ng-class="{ 'fa-github'   : type === 0,
                  'fa-linkedin' : type === 1,
                  'fa-skype' : type === 2,
                  'fa-google' : type === 3 }"></i>



                  Icons from Font Awesome







                  share|improve this answer


























                  • what a strange syntax, && should mean AND, like in any other c inspired language

                    – Pizzaiola Gorgonzola
                    Mar 18 '14 at 23:16






                  • 3





                    @PizzaiolaGorgonzola && does mean AND and || does mean OR. It's a clever hack using the short-circuit logic almost as a case/switch statement...

                    – Stein G. Strindhaug
                    Apr 1 '14 at 14:25











                  • Thanks mit. I didn't realized of that detail.

                    – Timbergus
                    Nov 1 '15 at 13:37











                  • The new update section worked like a charm! +1 for it!

                    – Matias
                    Jul 12 '16 at 18:36











                  • used the example of ng-class as mentioned in New Update, worked pretty well for me. Pretty sleek

                    – Acewin
                    Feb 16 '17 at 18:07
















                  105














                  I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>). It seems that when you inspect the element with Developer Tools, the element.style has no style assigned. So instead of using ng-class, I have tried using ng-style, and in this case, the new CSS attribute does appear inside element.style. This code works great for me:



                  <tr ng-repeat="element in collection">

                  [...amazing code...]

                  <td ng-style="myvar === 0 && {'background-color': 'red'} ||
                  myvar === 1 && {'background-color': 'green'} ||
                  myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>

                  [...more amazing code...]

                  </tr>


                  Myvar is what I am evaluating, and in each case I apply a style to each <td> depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.



                  UPDATE



                  If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:



                  <li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">


                  Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a OR we are in route_b, the active class will be applied.



                  This works just having a logic function on the right that returns true or false.



                  So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.



                  By the way, I forgot to give you the function isActive():



                  $rootScope.isActive = function(viewLocation) {
                  return viewLocation === $location.path();
                  };


                  NEW UPDATE



                  Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div, you can use the following code (very useful in ng-repeat):



                  <i class="fa" ng-class="{ 'fa-github'   : type === 0,
                  'fa-linkedin' : type === 1,
                  'fa-skype' : type === 2,
                  'fa-google' : type === 3 }"></i>



                  Icons from Font Awesome







                  share|improve this answer


























                  • what a strange syntax, && should mean AND, like in any other c inspired language

                    – Pizzaiola Gorgonzola
                    Mar 18 '14 at 23:16






                  • 3





                    @PizzaiolaGorgonzola && does mean AND and || does mean OR. It's a clever hack using the short-circuit logic almost as a case/switch statement...

                    – Stein G. Strindhaug
                    Apr 1 '14 at 14:25











                  • Thanks mit. I didn't realized of that detail.

                    – Timbergus
                    Nov 1 '15 at 13:37











                  • The new update section worked like a charm! +1 for it!

                    – Matias
                    Jul 12 '16 at 18:36











                  • used the example of ng-class as mentioned in New Update, worked pretty well for me. Pretty sleek

                    – Acewin
                    Feb 16 '17 at 18:07














                  105












                  105








                  105







                  I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>). It seems that when you inspect the element with Developer Tools, the element.style has no style assigned. So instead of using ng-class, I have tried using ng-style, and in this case, the new CSS attribute does appear inside element.style. This code works great for me:



                  <tr ng-repeat="element in collection">

                  [...amazing code...]

                  <td ng-style="myvar === 0 && {'background-color': 'red'} ||
                  myvar === 1 && {'background-color': 'green'} ||
                  myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>

                  [...more amazing code...]

                  </tr>


                  Myvar is what I am evaluating, and in each case I apply a style to each <td> depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.



                  UPDATE



                  If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:



                  <li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">


                  Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a OR we are in route_b, the active class will be applied.



                  This works just having a logic function on the right that returns true or false.



                  So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.



                  By the way, I forgot to give you the function isActive():



                  $rootScope.isActive = function(viewLocation) {
                  return viewLocation === $location.path();
                  };


                  NEW UPDATE



                  Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div, you can use the following code (very useful in ng-repeat):



                  <i class="fa" ng-class="{ 'fa-github'   : type === 0,
                  'fa-linkedin' : type === 1,
                  'fa-skype' : type === 2,
                  'fa-google' : type === 3 }"></i>



                  Icons from Font Awesome







                  share|improve this answer















                  I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>). It seems that when you inspect the element with Developer Tools, the element.style has no style assigned. So instead of using ng-class, I have tried using ng-style, and in this case, the new CSS attribute does appear inside element.style. This code works great for me:



                  <tr ng-repeat="element in collection">

                  [...amazing code...]

                  <td ng-style="myvar === 0 && {'background-color': 'red'} ||
                  myvar === 1 && {'background-color': 'green'} ||
                  myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>

                  [...more amazing code...]

                  </tr>


                  Myvar is what I am evaluating, and in each case I apply a style to each <td> depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.



                  UPDATE



                  If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:



                  <li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">


                  Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a OR we are in route_b, the active class will be applied.



                  This works just having a logic function on the right that returns true or false.



                  So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.



                  By the way, I forgot to give you the function isActive():



                  $rootScope.isActive = function(viewLocation) {
                  return viewLocation === $location.path();
                  };


                  NEW UPDATE



                  Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div, you can use the following code (very useful in ng-repeat):



                  <i class="fa" ng-class="{ 'fa-github'   : type === 0,
                  'fa-linkedin' : type === 1,
                  'fa-skype' : type === 2,
                  'fa-google' : type === 3 }"></i>



                  Icons from Font Awesome








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 30 '15 at 15:55









                  mit

                  6,15363460




                  6,15363460










                  answered Sep 20 '13 at 6:57









                  TimbergusTimbergus

                  2,58222627




                  2,58222627













                  • what a strange syntax, && should mean AND, like in any other c inspired language

                    – Pizzaiola Gorgonzola
                    Mar 18 '14 at 23:16






                  • 3





                    @PizzaiolaGorgonzola && does mean AND and || does mean OR. It's a clever hack using the short-circuit logic almost as a case/switch statement...

                    – Stein G. Strindhaug
                    Apr 1 '14 at 14:25











                  • Thanks mit. I didn't realized of that detail.

                    – Timbergus
                    Nov 1 '15 at 13:37











                  • The new update section worked like a charm! +1 for it!

                    – Matias
                    Jul 12 '16 at 18:36











                  • used the example of ng-class as mentioned in New Update, worked pretty well for me. Pretty sleek

                    – Acewin
                    Feb 16 '17 at 18:07



















                  • what a strange syntax, && should mean AND, like in any other c inspired language

                    – Pizzaiola Gorgonzola
                    Mar 18 '14 at 23:16






                  • 3





                    @PizzaiolaGorgonzola && does mean AND and || does mean OR. It's a clever hack using the short-circuit logic almost as a case/switch statement...

                    – Stein G. Strindhaug
                    Apr 1 '14 at 14:25











                  • Thanks mit. I didn't realized of that detail.

                    – Timbergus
                    Nov 1 '15 at 13:37











                  • The new update section worked like a charm! +1 for it!

                    – Matias
                    Jul 12 '16 at 18:36











                  • used the example of ng-class as mentioned in New Update, worked pretty well for me. Pretty sleek

                    – Acewin
                    Feb 16 '17 at 18:07

















                  what a strange syntax, && should mean AND, like in any other c inspired language

                  – Pizzaiola Gorgonzola
                  Mar 18 '14 at 23:16





                  what a strange syntax, && should mean AND, like in any other c inspired language

                  – Pizzaiola Gorgonzola
                  Mar 18 '14 at 23:16




                  3




                  3





                  @PizzaiolaGorgonzola && does mean AND and || does mean OR. It's a clever hack using the short-circuit logic almost as a case/switch statement...

                  – Stein G. Strindhaug
                  Apr 1 '14 at 14:25





                  @PizzaiolaGorgonzola && does mean AND and || does mean OR. It's a clever hack using the short-circuit logic almost as a case/switch statement...

                  – Stein G. Strindhaug
                  Apr 1 '14 at 14:25













                  Thanks mit. I didn't realized of that detail.

                  – Timbergus
                  Nov 1 '15 at 13:37





                  Thanks mit. I didn't realized of that detail.

                  – Timbergus
                  Nov 1 '15 at 13:37













                  The new update section worked like a charm! +1 for it!

                  – Matias
                  Jul 12 '16 at 18:36





                  The new update section worked like a charm! +1 for it!

                  – Matias
                  Jul 12 '16 at 18:36













                  used the example of ng-class as mentioned in New Update, worked pretty well for me. Pretty sleek

                  – Acewin
                  Feb 16 '17 at 18:07





                  used the example of ng-class as mentioned in New Update, worked pretty well for me. Pretty sleek

                  – Acewin
                  Feb 16 '17 at 18:07











                  34














                  This works well when ng-class can't be used (for example when styling SVG):



                  ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"


                  (I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)



                  I have published an article on working with AngularJS+SVG. It talks about this issue and numerous others. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS






                  share|improve this answer


























                  • I don't see any mention of ng-attr in the 1.1.4 docs -- do you have a link?

                    – Mark Rajcok
                    May 21 '13 at 17:28











                  • Sorry don't have a link. I found out about it by following the Angular forums, although I can't remember the exact page sorry.

                    – Ashley Davis
                    Jun 10 '13 at 3:59






                  • 1





                    The latest docs (v1.2) describe ng-attr- on the directives page, section ngAttr attribute bindings.

                    – Mark Rajcok
                    Aug 21 '13 at 12:50











                  • With 1.2, this becomes a great answer. ng-class doesn't let you perform logic, but ng-attr-class does. They both have their uses, but I can bet a lot of developers will be looking for ng-attr-class.

                    – Hylianpuffball
                    Jan 6 '14 at 21:32











                  • I got this to work well when other solutions provided here failed. Thank you.

                    – dps
                    Feb 21 '18 at 6:41
















                  34














                  This works well when ng-class can't be used (for example when styling SVG):



                  ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"


                  (I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)



                  I have published an article on working with AngularJS+SVG. It talks about this issue and numerous others. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS






                  share|improve this answer


























                  • I don't see any mention of ng-attr in the 1.1.4 docs -- do you have a link?

                    – Mark Rajcok
                    May 21 '13 at 17:28











                  • Sorry don't have a link. I found out about it by following the Angular forums, although I can't remember the exact page sorry.

                    – Ashley Davis
                    Jun 10 '13 at 3:59






                  • 1





                    The latest docs (v1.2) describe ng-attr- on the directives page, section ngAttr attribute bindings.

                    – Mark Rajcok
                    Aug 21 '13 at 12:50











                  • With 1.2, this becomes a great answer. ng-class doesn't let you perform logic, but ng-attr-class does. They both have their uses, but I can bet a lot of developers will be looking for ng-attr-class.

                    – Hylianpuffball
                    Jan 6 '14 at 21:32











                  • I got this to work well when other solutions provided here failed. Thank you.

                    – dps
                    Feb 21 '18 at 6:41














                  34












                  34








                  34







                  This works well when ng-class can't be used (for example when styling SVG):



                  ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"


                  (I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)



                  I have published an article on working with AngularJS+SVG. It talks about this issue and numerous others. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS






                  share|improve this answer















                  This works well when ng-class can't be used (for example when styling SVG):



                  ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"


                  (I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)



                  I have published an article on working with AngularJS+SVG. It talks about this issue and numerous others. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 19 '14 at 7:14

























                  answered May 21 '13 at 12:09









                  Ashley DavisAshley Davis

                  7,50964768




                  7,50964768













                  • I don't see any mention of ng-attr in the 1.1.4 docs -- do you have a link?

                    – Mark Rajcok
                    May 21 '13 at 17:28











                  • Sorry don't have a link. I found out about it by following the Angular forums, although I can't remember the exact page sorry.

                    – Ashley Davis
                    Jun 10 '13 at 3:59






                  • 1





                    The latest docs (v1.2) describe ng-attr- on the directives page, section ngAttr attribute bindings.

                    – Mark Rajcok
                    Aug 21 '13 at 12:50











                  • With 1.2, this becomes a great answer. ng-class doesn't let you perform logic, but ng-attr-class does. They both have their uses, but I can bet a lot of developers will be looking for ng-attr-class.

                    – Hylianpuffball
                    Jan 6 '14 at 21:32











                  • I got this to work well when other solutions provided here failed. Thank you.

                    – dps
                    Feb 21 '18 at 6:41



















                  • I don't see any mention of ng-attr in the 1.1.4 docs -- do you have a link?

                    – Mark Rajcok
                    May 21 '13 at 17:28











                  • Sorry don't have a link. I found out about it by following the Angular forums, although I can't remember the exact page sorry.

                    – Ashley Davis
                    Jun 10 '13 at 3:59






                  • 1





                    The latest docs (v1.2) describe ng-attr- on the directives page, section ngAttr attribute bindings.

                    – Mark Rajcok
                    Aug 21 '13 at 12:50











                  • With 1.2, this becomes a great answer. ng-class doesn't let you perform logic, but ng-attr-class does. They both have their uses, but I can bet a lot of developers will be looking for ng-attr-class.

                    – Hylianpuffball
                    Jan 6 '14 at 21:32











                  • I got this to work well when other solutions provided here failed. Thank you.

                    – dps
                    Feb 21 '18 at 6:41

















                  I don't see any mention of ng-attr in the 1.1.4 docs -- do you have a link?

                  – Mark Rajcok
                  May 21 '13 at 17:28





                  I don't see any mention of ng-attr in the 1.1.4 docs -- do you have a link?

                  – Mark Rajcok
                  May 21 '13 at 17:28













                  Sorry don't have a link. I found out about it by following the Angular forums, although I can't remember the exact page sorry.

                  – Ashley Davis
                  Jun 10 '13 at 3:59





                  Sorry don't have a link. I found out about it by following the Angular forums, although I can't remember the exact page sorry.

                  – Ashley Davis
                  Jun 10 '13 at 3:59




                  1




                  1





                  The latest docs (v1.2) describe ng-attr- on the directives page, section ngAttr attribute bindings.

                  – Mark Rajcok
                  Aug 21 '13 at 12:50





                  The latest docs (v1.2) describe ng-attr- on the directives page, section ngAttr attribute bindings.

                  – Mark Rajcok
                  Aug 21 '13 at 12:50













                  With 1.2, this becomes a great answer. ng-class doesn't let you perform logic, but ng-attr-class does. They both have their uses, but I can bet a lot of developers will be looking for ng-attr-class.

                  – Hylianpuffball
                  Jan 6 '14 at 21:32





                  With 1.2, this becomes a great answer. ng-class doesn't let you perform logic, but ng-attr-class does. They both have their uses, but I can bet a lot of developers will be looking for ng-attr-class.

                  – Hylianpuffball
                  Jan 6 '14 at 21:32













                  I got this to work well when other solutions provided here failed. Thank you.

                  – dps
                  Feb 21 '18 at 6:41





                  I got this to work well when other solutions provided here failed. Thank you.

                  – dps
                  Feb 21 '18 at 6:41











                  12














                  span class="circle circle-{{selectcss(document.Extension)}}">


                  and code



                  $scope.selectcss = function (data) {
                  if (data == '.pdf')
                  return 'circle circle-pdf';
                  else
                  return 'circle circle-small';
                  };


                  css



                  .circle-pdf {
                  width: 24px;
                  height: 24px;
                  font-size: 16px;
                  font-weight: 700;
                  padding-top: 3px;
                  -webkit-border-radius: 12px;
                  -moz-border-radius: 12px;
                  border-radius: 12px;
                  background-image: url(images/pdf_icon32.png);
                  }





                  share|improve this answer


























                  • Always avoid the iF word

                    – LastTribunal
                    Jul 27 '15 at 22:56











                  • @LastTribunal why?

                    – iamserious
                    Aug 17 '15 at 10:55











                  • I want to encourage to avoid directly using the class-attribute. This will overwrite changes made by other plugins on this element.

                    – SimonSimCity
                    Jun 21 '17 at 13:26
















                  12














                  span class="circle circle-{{selectcss(document.Extension)}}">


                  and code



                  $scope.selectcss = function (data) {
                  if (data == '.pdf')
                  return 'circle circle-pdf';
                  else
                  return 'circle circle-small';
                  };


                  css



                  .circle-pdf {
                  width: 24px;
                  height: 24px;
                  font-size: 16px;
                  font-weight: 700;
                  padding-top: 3px;
                  -webkit-border-radius: 12px;
                  -moz-border-radius: 12px;
                  border-radius: 12px;
                  background-image: url(images/pdf_icon32.png);
                  }





                  share|improve this answer


























                  • Always avoid the iF word

                    – LastTribunal
                    Jul 27 '15 at 22:56











                  • @LastTribunal why?

                    – iamserious
                    Aug 17 '15 at 10:55











                  • I want to encourage to avoid directly using the class-attribute. This will overwrite changes made by other plugins on this element.

                    – SimonSimCity
                    Jun 21 '17 at 13:26














                  12












                  12








                  12







                  span class="circle circle-{{selectcss(document.Extension)}}">


                  and code



                  $scope.selectcss = function (data) {
                  if (data == '.pdf')
                  return 'circle circle-pdf';
                  else
                  return 'circle circle-small';
                  };


                  css



                  .circle-pdf {
                  width: 24px;
                  height: 24px;
                  font-size: 16px;
                  font-weight: 700;
                  padding-top: 3px;
                  -webkit-border-radius: 12px;
                  -moz-border-radius: 12px;
                  border-radius: 12px;
                  background-image: url(images/pdf_icon32.png);
                  }





                  share|improve this answer















                  span class="circle circle-{{selectcss(document.Extension)}}">


                  and code



                  $scope.selectcss = function (data) {
                  if (data == '.pdf')
                  return 'circle circle-pdf';
                  else
                  return 'circle circle-small';
                  };


                  css



                  .circle-pdf {
                  width: 24px;
                  height: 24px;
                  font-size: 16px;
                  font-weight: 700;
                  padding-top: 3px;
                  -webkit-border-radius: 12px;
                  -moz-border-radius: 12px;
                  border-radius: 12px;
                  background-image: url(images/pdf_icon32.png);
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 31 '15 at 12:03









                  yegor256

                  57k90368511




                  57k90368511










                  answered Sep 9 '14 at 19:05









                  Nenad JesicNenad Jesic

                  12112




                  12112













                  • Always avoid the iF word

                    – LastTribunal
                    Jul 27 '15 at 22:56











                  • @LastTribunal why?

                    – iamserious
                    Aug 17 '15 at 10:55











                  • I want to encourage to avoid directly using the class-attribute. This will overwrite changes made by other plugins on this element.

                    – SimonSimCity
                    Jun 21 '17 at 13:26



















                  • Always avoid the iF word

                    – LastTribunal
                    Jul 27 '15 at 22:56











                  • @LastTribunal why?

                    – iamserious
                    Aug 17 '15 at 10:55











                  • I want to encourage to avoid directly using the class-attribute. This will overwrite changes made by other plugins on this element.

                    – SimonSimCity
                    Jun 21 '17 at 13:26

















                  Always avoid the iF word

                  – LastTribunal
                  Jul 27 '15 at 22:56





                  Always avoid the iF word

                  – LastTribunal
                  Jul 27 '15 at 22:56













                  @LastTribunal why?

                  – iamserious
                  Aug 17 '15 at 10:55





                  @LastTribunal why?

                  – iamserious
                  Aug 17 '15 at 10:55













                  I want to encourage to avoid directly using the class-attribute. This will overwrite changes made by other plugins on this element.

                  – SimonSimCity
                  Jun 21 '17 at 13:26





                  I want to encourage to avoid directly using the class-attribute. This will overwrite changes made by other plugins on this element.

                  – SimonSimCity
                  Jun 21 '17 at 13:26











                  10














                  This solution did the trick for me



                  <a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>





                  share|improve this answer




























                    10














                    This solution did the trick for me



                    <a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>





                    share|improve this answer


























                      10












                      10








                      10







                      This solution did the trick for me



                      <a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>





                      share|improve this answer













                      This solution did the trick for me



                      <a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 23 '14 at 19:25









                      iamtankistiamtankist

                      2,45011323




                      2,45011323























                          7














                          Another option when you need a simple css style of one or two properties:



                          View:



                          <tr ng-repeat="element in collection">
                          [...amazing code...]
                          <td ng-style="{'background-color': getTrColor(element.myvar)}">
                          {{ element.myvar }}
                          </td>
                          [...more amazing code...]
                          </tr>


                          Controller:



                          $scope.getTrColor = function (colorIndex) {
                          switch(colorIndex){
                          case 0: return 'red';
                          case 1: return 'green';
                          default: return 'yellow';
                          }
                          };





                          share|improve this answer






























                            7














                            Another option when you need a simple css style of one or two properties:



                            View:



                            <tr ng-repeat="element in collection">
                            [...amazing code...]
                            <td ng-style="{'background-color': getTrColor(element.myvar)}">
                            {{ element.myvar }}
                            </td>
                            [...more amazing code...]
                            </tr>


                            Controller:



                            $scope.getTrColor = function (colorIndex) {
                            switch(colorIndex){
                            case 0: return 'red';
                            case 1: return 'green';
                            default: return 'yellow';
                            }
                            };





                            share|improve this answer




























                              7












                              7








                              7







                              Another option when you need a simple css style of one or two properties:



                              View:



                              <tr ng-repeat="element in collection">
                              [...amazing code...]
                              <td ng-style="{'background-color': getTrColor(element.myvar)}">
                              {{ element.myvar }}
                              </td>
                              [...more amazing code...]
                              </tr>


                              Controller:



                              $scope.getTrColor = function (colorIndex) {
                              switch(colorIndex){
                              case 0: return 'red';
                              case 1: return 'green';
                              default: return 'yellow';
                              }
                              };





                              share|improve this answer















                              Another option when you need a simple css style of one or two properties:



                              View:



                              <tr ng-repeat="element in collection">
                              [...amazing code...]
                              <td ng-style="{'background-color': getTrColor(element.myvar)}">
                              {{ element.myvar }}
                              </td>
                              [...more amazing code...]
                              </tr>


                              Controller:



                              $scope.getTrColor = function (colorIndex) {
                              switch(colorIndex){
                              case 0: return 'red';
                              case 1: return 'green';
                              default: return 'yellow';
                              }
                              };






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Mar 23 '17 at 8:23









                              masud_moni

                              7571225




                              7571225










                              answered Mar 6 '16 at 16:08









                              DudiDudi

                              2,29511822




                              2,29511822























                                  7














                                  You can use ternary expression. There are two ways to do this:



                                  <div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>


                                  or...



                                  <div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>





                                  share|improve this answer





















                                  • 1





                                    Maybe u will find it better: <div ng-style="{ 'color': (myVariable > 100)? 'red' : 'blue' }"></div>

                                    – Dudi
                                    Mar 3 '18 at 7:19











                                  • Dudi, if not better, just as useful, so I added it to @maykel's "ternary expression" answer. Thanks to both of you!

                                    – jbobbins
                                    May 19 '18 at 6:43


















                                  7














                                  You can use ternary expression. There are two ways to do this:



                                  <div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>


                                  or...



                                  <div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>





                                  share|improve this answer





















                                  • 1





                                    Maybe u will find it better: <div ng-style="{ 'color': (myVariable > 100)? 'red' : 'blue' }"></div>

                                    – Dudi
                                    Mar 3 '18 at 7:19











                                  • Dudi, if not better, just as useful, so I added it to @maykel's "ternary expression" answer. Thanks to both of you!

                                    – jbobbins
                                    May 19 '18 at 6:43
















                                  7












                                  7








                                  7







                                  You can use ternary expression. There are two ways to do this:



                                  <div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>


                                  or...



                                  <div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>





                                  share|improve this answer















                                  You can use ternary expression. There are two ways to do this:



                                  <div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>


                                  or...



                                  <div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Sep 27 '18 at 5:24









                                  Paul Rooney

                                  12.8k72845




                                  12.8k72845










                                  answered Jan 31 '17 at 11:48









                                  michal-michalakmichal-michalak

                                  18124




                                  18124








                                  • 1





                                    Maybe u will find it better: <div ng-style="{ 'color': (myVariable > 100)? 'red' : 'blue' }"></div>

                                    – Dudi
                                    Mar 3 '18 at 7:19











                                  • Dudi, if not better, just as useful, so I added it to @maykel's "ternary expression" answer. Thanks to both of you!

                                    – jbobbins
                                    May 19 '18 at 6:43
















                                  • 1





                                    Maybe u will find it better: <div ng-style="{ 'color': (myVariable > 100)? 'red' : 'blue' }"></div>

                                    – Dudi
                                    Mar 3 '18 at 7:19











                                  • Dudi, if not better, just as useful, so I added it to @maykel's "ternary expression" answer. Thanks to both of you!

                                    – jbobbins
                                    May 19 '18 at 6:43










                                  1




                                  1





                                  Maybe u will find it better: <div ng-style="{ 'color': (myVariable > 100)? 'red' : 'blue' }"></div>

                                  – Dudi
                                  Mar 3 '18 at 7:19





                                  Maybe u will find it better: <div ng-style="{ 'color': (myVariable > 100)? 'red' : 'blue' }"></div>

                                  – Dudi
                                  Mar 3 '18 at 7:19













                                  Dudi, if not better, just as useful, so I added it to @maykel's "ternary expression" answer. Thanks to both of you!

                                  – jbobbins
                                  May 19 '18 at 6:43







                                  Dudi, if not better, just as useful, so I added it to @maykel's "ternary expression" answer. Thanks to both of you!

                                  – jbobbins
                                  May 19 '18 at 6:43













                                  6














                                  See the following example



                                  <!DOCTYPE html>
                                  <html ng-app>
                                  <head>
                                  <title>Demo Changing CSS Classes Conditionally with Angular</title>
                                  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
                                  <script src="res/js/controllers.js"></script>

                                  <style>

                                  .checkboxList {
                                  border:1px solid #000;
                                  background-color:#fff;
                                  color:#000;
                                  width:300px;
                                  height: 100px;
                                  overflow-y: scroll;
                                  }

                                  .uncheckedClass {
                                  background-color:#eeeeee;
                                  color:black;
                                  }
                                  .checkedClass {
                                  background-color:#3ab44a;
                                  color:white;
                                  }
                                  </style>

                                  </head>
                                  <body ng-controller="TeamListCtrl">
                                  <b>Teams</b>
                                  <div id="teamCheckboxList" class="checkboxList">

                                  <div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">

                                  <label>
                                  <input type="checkbox" ng-model="team.isChecked" />
                                  <span>{{team.name}}</span>
                                  </label>
                                  </div>
                                  </div>
                                  </body>
                                  </html>





                                  share|improve this answer




























                                    6














                                    See the following example



                                    <!DOCTYPE html>
                                    <html ng-app>
                                    <head>
                                    <title>Demo Changing CSS Classes Conditionally with Angular</title>
                                    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
                                    <script src="res/js/controllers.js"></script>

                                    <style>

                                    .checkboxList {
                                    border:1px solid #000;
                                    background-color:#fff;
                                    color:#000;
                                    width:300px;
                                    height: 100px;
                                    overflow-y: scroll;
                                    }

                                    .uncheckedClass {
                                    background-color:#eeeeee;
                                    color:black;
                                    }
                                    .checkedClass {
                                    background-color:#3ab44a;
                                    color:white;
                                    }
                                    </style>

                                    </head>
                                    <body ng-controller="TeamListCtrl">
                                    <b>Teams</b>
                                    <div id="teamCheckboxList" class="checkboxList">

                                    <div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">

                                    <label>
                                    <input type="checkbox" ng-model="team.isChecked" />
                                    <span>{{team.name}}</span>
                                    </label>
                                    </div>
                                    </div>
                                    </body>
                                    </html>





                                    share|improve this answer


























                                      6












                                      6








                                      6







                                      See the following example



                                      <!DOCTYPE html>
                                      <html ng-app>
                                      <head>
                                      <title>Demo Changing CSS Classes Conditionally with Angular</title>
                                      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
                                      <script src="res/js/controllers.js"></script>

                                      <style>

                                      .checkboxList {
                                      border:1px solid #000;
                                      background-color:#fff;
                                      color:#000;
                                      width:300px;
                                      height: 100px;
                                      overflow-y: scroll;
                                      }

                                      .uncheckedClass {
                                      background-color:#eeeeee;
                                      color:black;
                                      }
                                      .checkedClass {
                                      background-color:#3ab44a;
                                      color:white;
                                      }
                                      </style>

                                      </head>
                                      <body ng-controller="TeamListCtrl">
                                      <b>Teams</b>
                                      <div id="teamCheckboxList" class="checkboxList">

                                      <div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">

                                      <label>
                                      <input type="checkbox" ng-model="team.isChecked" />
                                      <span>{{team.name}}</span>
                                      </label>
                                      </div>
                                      </div>
                                      </body>
                                      </html>





                                      share|improve this answer













                                      See the following example



                                      <!DOCTYPE html>
                                      <html ng-app>
                                      <head>
                                      <title>Demo Changing CSS Classes Conditionally with Angular</title>
                                      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
                                      <script src="res/js/controllers.js"></script>

                                      <style>

                                      .checkboxList {
                                      border:1px solid #000;
                                      background-color:#fff;
                                      color:#000;
                                      width:300px;
                                      height: 100px;
                                      overflow-y: scroll;
                                      }

                                      .uncheckedClass {
                                      background-color:#eeeeee;
                                      color:black;
                                      }
                                      .checkedClass {
                                      background-color:#3ab44a;
                                      color:white;
                                      }
                                      </style>

                                      </head>
                                      <body ng-controller="TeamListCtrl">
                                      <b>Teams</b>
                                      <div id="teamCheckboxList" class="checkboxList">

                                      <div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">

                                      <label>
                                      <input type="checkbox" ng-model="team.isChecked" />
                                      <span>{{team.name}}</span>
                                      </label>
                                      </div>
                                      </div>
                                      </body>
                                      </html>






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 13 '14 at 6:58









                                      Ranga ReddyRanga Reddy

                                      1,76322130




                                      1,76322130























                                          2














                                          As of AngularJS v1.2.0rc, ng-class and even ng-attr-class fail with SVG elements (They did work earlier, even with normal binding inside the class attribute)



                                          Specifically, none of these work now:



                                          ng-class="current==this_element?'active':' ' "
                                          ng-attr-class="{{current==this_element?'active':' '}}"
                                          class="class1 class2 .... {{current==this_element?'active':''}}"


                                          As a workaround, I've to use



                                          ng-attr-otherAttr="{{current==this_element?'active':''}}"


                                          and then style using



                                          [otherAttr='active'] {
                                          ... styles ...
                                          }





                                          share|improve this answer




























                                            2














                                            As of AngularJS v1.2.0rc, ng-class and even ng-attr-class fail with SVG elements (They did work earlier, even with normal binding inside the class attribute)



                                            Specifically, none of these work now:



                                            ng-class="current==this_element?'active':' ' "
                                            ng-attr-class="{{current==this_element?'active':' '}}"
                                            class="class1 class2 .... {{current==this_element?'active':''}}"


                                            As a workaround, I've to use



                                            ng-attr-otherAttr="{{current==this_element?'active':''}}"


                                            and then style using



                                            [otherAttr='active'] {
                                            ... styles ...
                                            }





                                            share|improve this answer


























                                              2












                                              2








                                              2







                                              As of AngularJS v1.2.0rc, ng-class and even ng-attr-class fail with SVG elements (They did work earlier, even with normal binding inside the class attribute)



                                              Specifically, none of these work now:



                                              ng-class="current==this_element?'active':' ' "
                                              ng-attr-class="{{current==this_element?'active':' '}}"
                                              class="class1 class2 .... {{current==this_element?'active':''}}"


                                              As a workaround, I've to use



                                              ng-attr-otherAttr="{{current==this_element?'active':''}}"


                                              and then style using



                                              [otherAttr='active'] {
                                              ... styles ...
                                              }





                                              share|improve this answer













                                              As of AngularJS v1.2.0rc, ng-class and even ng-attr-class fail with SVG elements (They did work earlier, even with normal binding inside the class attribute)



                                              Specifically, none of these work now:



                                              ng-class="current==this_element?'active':' ' "
                                              ng-attr-class="{{current==this_element?'active':' '}}"
                                              class="class1 class2 .... {{current==this_element?'active':''}}"


                                              As a workaround, I've to use



                                              ng-attr-otherAttr="{{current==this_element?'active':''}}"


                                              and then style using



                                              [otherAttr='active'] {
                                              ... styles ...
                                              }






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Sep 15 '13 at 12:48









                                              kumar_harshkumar_harsh

                                              13.3k65786




                                              13.3k65786























                                                  1














                                                  One more (in the future) way to conditionally apply style is by conditionally creating scoped style



                                                  <style scoped type="text/css" ng-if="...">

                                                  </style>


                                                  But nowadays only FireFox supports scoped styles.






                                                  share|improve this answer




























                                                    1














                                                    One more (in the future) way to conditionally apply style is by conditionally creating scoped style



                                                    <style scoped type="text/css" ng-if="...">

                                                    </style>


                                                    But nowadays only FireFox supports scoped styles.






                                                    share|improve this answer


























                                                      1












                                                      1








                                                      1







                                                      One more (in the future) way to conditionally apply style is by conditionally creating scoped style



                                                      <style scoped type="text/css" ng-if="...">

                                                      </style>


                                                      But nowadays only FireFox supports scoped styles.






                                                      share|improve this answer













                                                      One more (in the future) way to conditionally apply style is by conditionally creating scoped style



                                                      <style scoped type="text/css" ng-if="...">

                                                      </style>


                                                      But nowadays only FireFox supports scoped styles.







                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Aug 19 '14 at 13:39









                                                      Pavel VoroninPavel Voronin

                                                      7,42354388




                                                      7,42354388























                                                          1














                                                          There is one more option that I recently discovered that some people may find useful because it allows you to change a CSS rule within a style element - thus avoiding the need for repeated use of an angular directive such as ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.



                                                          This option makes use of a service with service variables which are set by a controller and watched by an attribute-directive I call "custom-style". This strategy could be used in many different ways, and I attempted to provide some general guidance with this fiddle.



                                                          var app = angular.module('myApp', ['ui.bootstrap']);
                                                          app.service('MainService', function(){
                                                          var vm = this;
                                                          });
                                                          app.controller('MainCtrl', function(MainService){
                                                          var vm = this;
                                                          vm.ms = MainService;
                                                          });
                                                          app.directive('customStyle', function(MainService){
                                                          return {
                                                          restrict : 'A',
                                                          link : function(scope, element, attr){
                                                          var style = angular.element('<style></style>');
                                                          element.append(style);
                                                          scope.$watch(function(){ return MainService.theme; },
                                                          function(){
                                                          var css = '';
                                                          angular.forEach(MainService.theme, function(selector, key){
                                                          angular.forEach(MainService.theme[key], function(val, k){
                                                          css += key + ' { '+k+' : '+val+'} ';
                                                          });
                                                          });
                                                          style.html(css);
                                                          }, true);
                                                          }
                                                          };
                                                          });





                                                          share|improve this answer




























                                                            1














                                                            There is one more option that I recently discovered that some people may find useful because it allows you to change a CSS rule within a style element - thus avoiding the need for repeated use of an angular directive such as ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.



                                                            This option makes use of a service with service variables which are set by a controller and watched by an attribute-directive I call "custom-style". This strategy could be used in many different ways, and I attempted to provide some general guidance with this fiddle.



                                                            var app = angular.module('myApp', ['ui.bootstrap']);
                                                            app.service('MainService', function(){
                                                            var vm = this;
                                                            });
                                                            app.controller('MainCtrl', function(MainService){
                                                            var vm = this;
                                                            vm.ms = MainService;
                                                            });
                                                            app.directive('customStyle', function(MainService){
                                                            return {
                                                            restrict : 'A',
                                                            link : function(scope, element, attr){
                                                            var style = angular.element('<style></style>');
                                                            element.append(style);
                                                            scope.$watch(function(){ return MainService.theme; },
                                                            function(){
                                                            var css = '';
                                                            angular.forEach(MainService.theme, function(selector, key){
                                                            angular.forEach(MainService.theme[key], function(val, k){
                                                            css += key + ' { '+k+' : '+val+'} ';
                                                            });
                                                            });
                                                            style.html(css);
                                                            }, true);
                                                            }
                                                            };
                                                            });





                                                            share|improve this answer


























                                                              1












                                                              1








                                                              1







                                                              There is one more option that I recently discovered that some people may find useful because it allows you to change a CSS rule within a style element - thus avoiding the need for repeated use of an angular directive such as ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.



                                                              This option makes use of a service with service variables which are set by a controller and watched by an attribute-directive I call "custom-style". This strategy could be used in many different ways, and I attempted to provide some general guidance with this fiddle.



                                                              var app = angular.module('myApp', ['ui.bootstrap']);
                                                              app.service('MainService', function(){
                                                              var vm = this;
                                                              });
                                                              app.controller('MainCtrl', function(MainService){
                                                              var vm = this;
                                                              vm.ms = MainService;
                                                              });
                                                              app.directive('customStyle', function(MainService){
                                                              return {
                                                              restrict : 'A',
                                                              link : function(scope, element, attr){
                                                              var style = angular.element('<style></style>');
                                                              element.append(style);
                                                              scope.$watch(function(){ return MainService.theme; },
                                                              function(){
                                                              var css = '';
                                                              angular.forEach(MainService.theme, function(selector, key){
                                                              angular.forEach(MainService.theme[key], function(val, k){
                                                              css += key + ' { '+k+' : '+val+'} ';
                                                              });
                                                              });
                                                              style.html(css);
                                                              }, true);
                                                              }
                                                              };
                                                              });





                                                              share|improve this answer













                                                              There is one more option that I recently discovered that some people may find useful because it allows you to change a CSS rule within a style element - thus avoiding the need for repeated use of an angular directive such as ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.



                                                              This option makes use of a service with service variables which are set by a controller and watched by an attribute-directive I call "custom-style". This strategy could be used in many different ways, and I attempted to provide some general guidance with this fiddle.



                                                              var app = angular.module('myApp', ['ui.bootstrap']);
                                                              app.service('MainService', function(){
                                                              var vm = this;
                                                              });
                                                              app.controller('MainCtrl', function(MainService){
                                                              var vm = this;
                                                              vm.ms = MainService;
                                                              });
                                                              app.directive('customStyle', function(MainService){
                                                              return {
                                                              restrict : 'A',
                                                              link : function(scope, element, attr){
                                                              var style = angular.element('<style></style>');
                                                              element.append(style);
                                                              scope.$watch(function(){ return MainService.theme; },
                                                              function(){
                                                              var css = '';
                                                              angular.forEach(MainService.theme, function(selector, key){
                                                              angular.forEach(MainService.theme[key], function(val, k){
                                                              css += key + ' { '+k+' : '+val+'} ';
                                                              });
                                                              });
                                                              style.html(css);
                                                              }, true);
                                                              }
                                                              };
                                                              });






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Nov 7 '15 at 14:28









                                                              Gavin PalmerGavin Palmer

                                                              9151222




                                                              9151222























                                                                  1














                                                                  well i would suggest you to check condition in your controller with a function returning true or false .



                                                                  <div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>


                                                                  and in your controller check the condition



                                                                  $scope.getTodayForHighLight = function(today, date){
                                                                  return (today == date);
                                                                  }





                                                                  share|improve this answer






























                                                                    1














                                                                    well i would suggest you to check condition in your controller with a function returning true or false .



                                                                    <div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>


                                                                    and in your controller check the condition



                                                                    $scope.getTodayForHighLight = function(today, date){
                                                                    return (today == date);
                                                                    }





                                                                    share|improve this answer




























                                                                      1












                                                                      1








                                                                      1







                                                                      well i would suggest you to check condition in your controller with a function returning true or false .



                                                                      <div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>


                                                                      and in your controller check the condition



                                                                      $scope.getTodayForHighLight = function(today, date){
                                                                      return (today == date);
                                                                      }





                                                                      share|improve this answer















                                                                      well i would suggest you to check condition in your controller with a function returning true or false .



                                                                      <div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>


                                                                      and in your controller check the condition



                                                                      $scope.getTodayForHighLight = function(today, date){
                                                                      return (today == date);
                                                                      }






                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited Sep 27 '18 at 5:24









                                                                      Paul Rooney

                                                                      12.8k72845




                                                                      12.8k72845










                                                                      answered Jun 6 '15 at 11:13









                                                                      sheelpriysheelpriy

                                                                      1,1901323




                                                                      1,1901323























                                                                          0














                                                                          One thing to watch is - if the CSS style has dashes - you must remove them. So if you want to set background-color, the correct way is:



                                                                          ng-style="{backgroundColor:myColor}" 





                                                                          share|improve this answer





















                                                                          • 5





                                                                            No, you don't have to. ng-style="{'background-color':myColor}" works perfectly well.

                                                                            – gerasalus
                                                                            Jul 7 '14 at 10:26
















                                                                          0














                                                                          One thing to watch is - if the CSS style has dashes - you must remove them. So if you want to set background-color, the correct way is:



                                                                          ng-style="{backgroundColor:myColor}" 





                                                                          share|improve this answer





















                                                                          • 5





                                                                            No, you don't have to. ng-style="{'background-color':myColor}" works perfectly well.

                                                                            – gerasalus
                                                                            Jul 7 '14 at 10:26














                                                                          0












                                                                          0








                                                                          0







                                                                          One thing to watch is - if the CSS style has dashes - you must remove them. So if you want to set background-color, the correct way is:



                                                                          ng-style="{backgroundColor:myColor}" 





                                                                          share|improve this answer















                                                                          One thing to watch is - if the CSS style has dashes - you must remove them. So if you want to set background-color, the correct way is:



                                                                          ng-style="{backgroundColor:myColor}" 






                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Mar 5 '14 at 11:04









                                                                          ConcurrentHashMap

                                                                          3,94263348




                                                                          3,94263348










                                                                          answered Mar 5 '14 at 10:45









                                                                          Neil MunroNeil Munro

                                                                          173




                                                                          173








                                                                          • 5





                                                                            No, you don't have to. ng-style="{'background-color':myColor}" works perfectly well.

                                                                            – gerasalus
                                                                            Jul 7 '14 at 10:26














                                                                          • 5





                                                                            No, you don't have to. ng-style="{'background-color':myColor}" works perfectly well.

                                                                            – gerasalus
                                                                            Jul 7 '14 at 10:26








                                                                          5




                                                                          5





                                                                          No, you don't have to. ng-style="{'background-color':myColor}" works perfectly well.

                                                                          – gerasalus
                                                                          Jul 7 '14 at 10:26





                                                                          No, you don't have to. ng-style="{'background-color':myColor}" works perfectly well.

                                                                          – gerasalus
                                                                          Jul 7 '14 at 10:26











                                                                          0














                                                                          Here's how i conditionally applied gray text style on a disabled button



                                                                          import { Component } from '@angular/core';

                                                                          @Component({
                                                                          selector: 'my-app',
                                                                          styleUrls: [ './app.component.css' ],
                                                                          template: `
                                                                          <button
                                                                          (click)='buttonClick1()'
                                                                          [disabled] = "btnDisabled"
                                                                          [ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}">
                                                                          {{btnText}}
                                                                          </button>`
                                                                          })
                                                                          export class AppComponent {
                                                                          name = 'Angular';
                                                                          btnText = 'Click me';
                                                                          btnDisabled = false;
                                                                          buttonClick1() {
                                                                          this.btnDisabled = true;
                                                                          this.btnText = 'you clicked me';
                                                                          setTimeout(() => {
                                                                          this.btnText = 'click me again';
                                                                          this.btnDisabled = false
                                                                          }, 5000);
                                                                          }
                                                                          }


                                                                          Here's a working example:
                                                                          https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html






                                                                          share|improve this answer




























                                                                            0














                                                                            Here's how i conditionally applied gray text style on a disabled button



                                                                            import { Component } from '@angular/core';

                                                                            @Component({
                                                                            selector: 'my-app',
                                                                            styleUrls: [ './app.component.css' ],
                                                                            template: `
                                                                            <button
                                                                            (click)='buttonClick1()'
                                                                            [disabled] = "btnDisabled"
                                                                            [ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}">
                                                                            {{btnText}}
                                                                            </button>`
                                                                            })
                                                                            export class AppComponent {
                                                                            name = 'Angular';
                                                                            btnText = 'Click me';
                                                                            btnDisabled = false;
                                                                            buttonClick1() {
                                                                            this.btnDisabled = true;
                                                                            this.btnText = 'you clicked me';
                                                                            setTimeout(() => {
                                                                            this.btnText = 'click me again';
                                                                            this.btnDisabled = false
                                                                            }, 5000);
                                                                            }
                                                                            }


                                                                            Here's a working example:
                                                                            https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html






                                                                            share|improve this answer


























                                                                              0












                                                                              0








                                                                              0







                                                                              Here's how i conditionally applied gray text style on a disabled button



                                                                              import { Component } from '@angular/core';

                                                                              @Component({
                                                                              selector: 'my-app',
                                                                              styleUrls: [ './app.component.css' ],
                                                                              template: `
                                                                              <button
                                                                              (click)='buttonClick1()'
                                                                              [disabled] = "btnDisabled"
                                                                              [ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}">
                                                                              {{btnText}}
                                                                              </button>`
                                                                              })
                                                                              export class AppComponent {
                                                                              name = 'Angular';
                                                                              btnText = 'Click me';
                                                                              btnDisabled = false;
                                                                              buttonClick1() {
                                                                              this.btnDisabled = true;
                                                                              this.btnText = 'you clicked me';
                                                                              setTimeout(() => {
                                                                              this.btnText = 'click me again';
                                                                              this.btnDisabled = false
                                                                              }, 5000);
                                                                              }
                                                                              }


                                                                              Here's a working example:
                                                                              https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html






                                                                              share|improve this answer













                                                                              Here's how i conditionally applied gray text style on a disabled button



                                                                              import { Component } from '@angular/core';

                                                                              @Component({
                                                                              selector: 'my-app',
                                                                              styleUrls: [ './app.component.css' ],
                                                                              template: `
                                                                              <button
                                                                              (click)='buttonClick1()'
                                                                              [disabled] = "btnDisabled"
                                                                              [ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}">
                                                                              {{btnText}}
                                                                              </button>`
                                                                              })
                                                                              export class AppComponent {
                                                                              name = 'Angular';
                                                                              btnText = 'Click me';
                                                                              btnDisabled = false;
                                                                              buttonClick1() {
                                                                              this.btnDisabled = true;
                                                                              this.btnText = 'you clicked me';
                                                                              setTimeout(() => {
                                                                              this.btnText = 'click me again';
                                                                              this.btnDisabled = false
                                                                              }, 5000);
                                                                              }
                                                                              }


                                                                              Here's a working example:
                                                                              https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html







                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Jan 3 at 1:55









                                                                              BraveNewMathBraveNewMath

                                                                              5,05623445




                                                                              5,05623445

















                                                                                  protected by Pankaj Parkar Jun 10 '15 at 17:14



                                                                                  Thank you for your interest in this question.
                                                                                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                  Would you like to answer one of these unanswered questions instead?



                                                                                  Popular posts from this blog

                                                                                  Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                                                                  ts Property 'filter' does not exist on type '{}'

                                                                                  mat-slide-toggle shouldn't change it's state when I click cancel in confirmation window