Freddy Freddy - 3 months ago 13
AngularJS Question

Changes in ng-style have no effect to CSS-Style

I have a material design grid list with either one or two columns dependend of the screen size. If there is only one column (xs-screens) I want to give every second tile another background-color. In a two column layout the colored tiles should be diagonal, which means every first and fourth tile (in a block of four).

In HMTL all I do is calling a function within the ng-style attribute of md-grid-tile:

ng-style="{{getBackgroundColor($index)}}"


And in JavaScript the function is:

$scope.getBackgroundColor = function(index){
if($mdMedia("xs")){ //screen size extra-small
if(index % 2 === 0){
return "{'background-color':'lightgray'}";
}
} else {
if(index % 4 === 0 || index % 4 === 3){
return "{'background-color':'lightgray'}";
}
}
return "{'background-color':'white'}";
}


This code is working. Even if I change the screen size the function gets called and the ng-style attribute looks just as expected. But the style attribute doesn't cange anymore. Means the background-color remains like it was calculated in the beginning.

Why doesn't the style attribute change the way ng-style does? Here is also a complete code example: http://plnkr.co/edit/g3mP8gAoKn5ul9SU7rc3?p=preview

Any help would be appreciated.

Answer

use

<md-grid-tile ng-repeat="number in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
      layout-padding
      ng-style="{'background-color':getBackgroundColor($index)}">
      <label>Tile #{{$index}}</label>
    </md-grid-tile>

and from function return color directly

$scope.getBackgroundColor = function(index){
  if($mdMedia("xs")){ //screen size extra-small
    if(index % 2 === 0){
      return 'red';
    }
  } else {
    if(index % 4 === 0 || index % 4 === 3){
      return 'blue';
    }
  }
  return 'red';
}

here is working plunker http://plnkr.co/edit/3sfyHE559O2TkJogmPaW?p=preview

Comments