1

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?

2
  • 1
    Where is your newPriceInputElement element in your HTML provided here? Commented Sep 20, 2016 at 15:26
  • @DavidR that would be the <input>, I will edit the question to make that more clear. Commented Sep 20, 2016 at 15:28

2 Answers 2

3

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};
   }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, best way is using the controller and ngStyle.
This Worked for me as well. got more than 1 style,so i just create functions and it worked!
1

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

Or you can use ngClass that let you change dynamically 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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.