Nik Nik - 1 month ago 11
AngularJS Question

Trying to access scope variable in HTML with ng-style

Im trying to have the color of {{f.percentage}} to change depending on what the percentage is. I am able to generate the Red Green Blue values but I do not know how to use ng-style to write "color: rgb(red,green,blue)". Thanks

<div class="winPer" style="float:right;">
<span ng-style="{'color':
'rgb(' + f.red + ',' + f.green + ',' + f.blue + ')'}">{{f.winRate}}%</span>
</div>

Answer

I think you syntax is correct. Please check this working snippet.

angular.module('app', [])
  .controller('appCtrl', ['$scope',
    function($scope) {
      $scope.f = {
        red: '210',
        green: '20',
        blue: '20'
      }
      $scope.combineColor = function(f) {
        return 'rgb(' + f.red + ',' + f.green + ',' + f.blue + ')';
      }
    }
  ])

angular.element(document).ready(function() {
  angular.bootstrap(document, ['app'])
})
.container {
  width: 100%;
  height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div class="wrapper" ng-controller="appCtrl">

  <h2 ng-style="{'color': 'rgb(' + f.red + ',' + f.green + ',' + f.blue + ')'}">{{combineColor(f)}} </h2>

  <h2 ng-style="{'color': combineColor(f)}">{{combineColor(f)}} </h2>

</div>