5

I have and angularjs application that fetches data via api, and builds a webpage with it.

Usually I use ng-style to create dynamic styling, but now I have to use the nth-of-type attribute that can only be used in a css stylesheet (I cannot use individual styling since the number and order of elements always change).

I have tried this naive code (in the html page):

<style ng-if="styles.sc && styles.sc.length==3">
    a.mosection:nth-of-type(3n) > div {
        background-color: {{styles.sc[0]}} !important;
    }
    a.mosection:nth-of-type(3n+1) > div {
        background-color: {{styles.sc[1]}} !important;
    }
    a.mosection:nth-of-type(3n+2) > div {
        background-color: {{styles.sc[2]}} !important;
    }
</style>

But it didn't work... Apparently angular doesn't bind the data inside the style tag (the ng-if attribute does get digested properly)

Does anyone have any idea how this can be done?

Thanks!

2 Answers 2

4

You should checkout those three ng-*

https://docs.angularjs.org/api/ng/directive/ngClass https://docs.angularjs.org/api/ng/directive/ngClassOdd https://docs.angularjs.org/api/ng/directive/ngClassEven

all of them can accept functions as attributes, you can also checkout https://docs.angularjs.org/api/ng/directive/ngStyle

which might be actually the best in your case

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

Comments

0

Thanks! I indeed solved it by using ng-style with a function

The HTML

<div class="widget widget-people" ng-style="{backgroundColor: staggerBgColors('widget', 'widget-people', '#333333')}"></div>
<div class="widget widget-property" ng-style="{backgroundColor: staggerBgColors('widget', 'widget-property', '#24d10f')}"></div>

The scope function

$scope.staggerBgColors = function(elesClass, eleClass, defaultColor){
  if (!$scope.styles || !$scope.styles.sc || $scope.styles.sc.length!=3){
    return defaultColor;
  }else{
    var listItem = $('.'+eleClass);
    var n = $('.'+elesClass).index( listItem ) % 3;
    return '#' + $scope.preview.moment.sc[n];
  }
}

I had to implement the same functionality of the css property "nth-of-type" using jQuery, but it works prefectly!

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.