cssangularjsangularjs-directive

What is the difference between ng-class and ng-style?


ng-class and ng-style both seem to be methods of dynamically setting CSS classes. What is the difference between them?


Solution

  • ng-style is used to interpolate javascript object into style attribute, not css class.

    Following directive will be translated to style="color:red"

    ng-style="{color: 'red'}"
    

    And ng-class directive translates your object into class attribute.

    Following will be translated to class="deleted" when isDeleted variable is true.

    ng-class="{'deleted': isDeleted}"
    

    Note:

    There is one more use case for ng-style. If you want to interpolate something in style attribute, you should consider using ng-style. Otherwise, that would not work before Internet Explorer 11 as documentation suggests.

    So, instead of using style:

    style="width: {{progress}}"
    

    Use ng-style:

    ng-style="{'width':progress}"