简体   繁体   中英

Update CSS styles dynamically using AngularJS

I'm new to AngularJS and I'm not really sure how to create the effect I want using it.

I'd like to compare the values of two elements and conditionally update the CSS for the elements based on that comparison.

This seems very simple to do with jQuery or Vanilla JS, but I'm not sure how I can accomplish the same thing in an Angular app.

If I strip my code down, this is basically all I need to change.

HTML:

<table>
  <thead>
    <tr>
      <th>Minimum Price</th>
      <th>New Price</th>
    </tr>
  </thead>
  <tbody>
      <td ng-bind="sku.MinimumPrice"></td> <!-- value one -->
      <td>
        <input ng-model="sku.NewPrice" id="price-input"> <!-- value two -->
      </td>
  </tbody>
</table>

Pseudocode:

if (sku.NewPrice > sku.MinimumPrice) {
  #price-input.style.color='red'
}

So, what is the 'Angular' way to implement this?

Using ng-style tag :

<input ng-model="MinimumPrice"/>
<input ng-model="NewPrice"/>
<p ng-style="getStyle()">
 Text
</p>

function MyCtrl($scope) {

    $scope.getStyle = function(){
        var color = 'black';

        if ($scope.NewPrice > $scope.MinimumPrice) {
            color = 'red';
        }

        return {'color': color};
   }

}

Angular has ngStyle for this purpose. This attribute let you change dinamycally your CSS using expressions and conditions.

Or you can use ngClass that let you change dinamycally any DOM class (and this is better, I think).

Ussage for ngClass is:

<ANY ng-class="{class: condition}">

So...

Style.css

.red {
    color: red;
}

Template.html

<input ng-model="sku.NewPrice" id="price-input" ng-class="{red: sku.NewPrice > sku.MinimumPrice}"

Hope this helps you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM