jacob-on-stackoverflow jacob-on-stackoverflow - 1 year ago 90
AngularJS Question

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.


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


if (sku.NewPrice > sku.MinimumPrice) {

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

Answer Source

Using ng-style tag:

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

function MyCtrl($scope) {

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

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

        return {'color': color};

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download