Home > Enterprise >  Apply class based on integer value in an AngularJS expression
Apply class based on integer value in an AngularJS expression

Time:11-26

I'm calculating differences between 2 values then storing that value in a variable named "allCallsNet", I want to toggle a class based on if the number is a Positive or Negative number in my HTML, using AngularJS Expressions

Example:

{allCallsNet=allCallsWeek1 - allCallsWeek2;""}

<p ng-class"{{positive: (allCallsNet.value != 'Negative')}}">{{allCallsNet}}</p>

CodePudding user response:

And if you also need help checking the number sign this could help

angular.module('Stack', []).controller('MainCtrl', function($scope) {
  $scope.allCallsNet = 0;
  $scope.add = function() {
    $scope.allCallsNet  = 1;
  }
  $scope.sub = function() {
    $scope.allCallsNet -= 1;
  }
});
.negative {
  color: red;
}

.positive {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="Stack" ng-controller="MainCtrl">
  <!-- You can use the ternary operator, to exchange between classes -->
  <p ng-class="allCallsNet > 0 ? 'positive' : 'negative'">Start editing and see your changes reflected here!</p>
  <button ng-click="add()">Add</button>
  <button ng-click="sub()">Subtract</button>
  <p>{{ allCallsNet }}</p>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Try this:

<p [class.positive]="allCallsNet.value != 'Negative'" >{{allCallsNet}}</p>
  • Related