Reputation: 463
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?
Upvotes: 1
Views: 1265
Reputation: 1093
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 :)
Upvotes: 1
Reputation: 1463
<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};
}
}
Upvotes: 3