0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I thought I tried this, but maybe I had another error back then. It doesn't matter, your solution works! Thank you very much.
Happy to help happy coding
0

I would reccomend you to insert global breakpoint classname:

$scope.mdMedia = $mdMedia;

and in the body:

<body ng-app="myModule" ng-controller="myController" ng-cloak ng-class="{'xs':mdMedia('xs'), 'sm':mdMedia('sm')}">

and then styling in css using :nth-child selector:

.xs md-grid-tile:nth-child(even) {
    background: grey;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.