javascriptcssangularjsmeteormeteoric

Changing dynamically background CSS in Meteor-Angular app


I'm developing an AngularJS Ionic Meteor app, and I need to change the background color of the botton box of an ionic card depending of it contents (a float). The ranges are:

data<=80
81 < data <= 160
161 < data <= 233
234 < data<= 317
318 < data <= 400.

Is there a CSS way to do it, or an AngularJS way instead?


Solution

  • You could use ngClass. Just setup your CSS background-color properties and set in your controller the appropriate class, for example:

    var myApp = angular.module('myApp', []);
    
    function MyCtrl($scope) {
      $scope.submit = function() {
        if ($scope.data <= 80) $scope.rangeColor = "red";
        // Add more conditional statements
        else $scope.rangeColor = "blue";
      }
    }
    .card {
      border-style: solid;
    }
    .red {
      background-color: red;
    }
    .blue {
      background-color: blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <body ng-app="myApp">
      <div ng-controller="MyCtrl">
        <h4>Data:</h4>
        <form ng-submit="submit()">
          <input type="text" name="data" ng-model="data" required>
          <input type="submit" id="submit" value="Submit" />
        </form>
        <br />
        <div ng-class="rangeColor" class="card">
          <div class="item item-text-wrap">
            This is a basic Card which contains an item that has wrapping text.
          </div>
        </div>
      </div>
    </body>

    You could also implement the conditional statements in your HTML elements:

    var myApp = angular.module('myApp', []);
    
    function MyCtrl($scope) {
    
    }
    .card {
      border-style: solid;
    }
    .red {
      background-color: red;
    }
    .blue {
      background-color: blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <body ng-app="myApp">
      <div ng-controller="MyCtrl">
        <h4>Data:</h4>
        <input type="text" name="data" ng-model="data" required>
        <br />
        <br />
        <div ng-class="{'red': data <= 80, 'blue': data > 80}" class="card">
          <div class="item item-text-wrap">
            This is a basic Card which contains an item that has wrapping text.
          </div>
        </div>
      </div>
    </body>