Warm tip: This article is reproduced from stackoverflow.com, please click
angularjs background css html angularjs-ng-repeat

Split a div background color based on $index in ng-repeat

发布于 2020-03-27 10:28:59

I am building a new UI where I am doing ng-repeat on an array and displaying elements in the array as radio buttons - inline.

HTML:

<div class="sliderticks-container survey-v2-slider-background" role="radiogroup">
  <div class="sliderticks focus-presenter" ng-repeat="answer in $ctrl.question.choices | orderBy: answer.orderIndex track by $index">
  </div>
</div>

I included the class "survey-v2-slider-background" in outer div which sets the background of the container that holds these radio buttons. CSS:

.survey-v2-slider-background {
    background: rgba(202, 236, 244, 0.5)
}

.sliderticks-container {
            display: flex;
            position: relative;
            justify-content: space-between;
            padding: 0 17px;
            border-radius: 14px;
            cursor: pointer;
            .sliderticks {
                display: inline;

My requirement is to split the background color from left to right based on the radio button the user clicks. Suppose if the array has 7 elements and if the user clicks on element with index 4, the background color of the container should be different (say red) to left of index 4. To the right of index 4, it should be the default background color mentioned in css file for 'survey-v2-slider-background'.

Is there any way to get this?

I want the background split to look like this: enter image description here

What I tried:

I came across linear-gradient which I can use like below but that's static percentage. I want it to be dynamic based on index selected.

.survey-v2-slider-background {
    background: linear-gradient(to right, red 50%, rgba(202, 236, 244, 0.5) 0%);
}
Questioner
Kiran Pabbu
Viewed
60
Kiran Pabbu 2019-07-10 23:14

I did this in the lines of what @kendavidson mentioned. Added a new div with position: absolute and Instead of doing it in controller, I just added ng-style with percentage condition in the html.

<div class="sliderticks-background survey-v2-slider-selected-background" ng-style = "{ width: ($ctrl.selectedOptionOrderIndex/($ctrl.question.choices.length-1)) * 100 + '%' }"></div>