willedanielsson
willedanielsson

Reputation: 1333

Angular ngRepeat - Unique style for every element

So my problem is that i use ng-repeat in Angular and every item need to have a certain style.

I repeat and create different list items from a JSON which contains name and value. The name and value and shown but every element also has a progress bar. The value (width) of the bar should depend on the value for each element.

Here is a fiddle which demonstrates: http://jsfiddle.net/15yb42tj/

As you can see in the fiddle, the width of the bar is 50% (as default in the CSS). However, for example the second element Karl which have the value 4, I want the bar to have a width of 40%.

Basically what I want to do for each element is:

$scope.bar_style = {
    'width' : "(parts.value)*10"
} 

I've been trying different strategies but honestly I have just been shooting in the dark, does anyone here know how to style a certain element in a ngRepeat?

Upvotes: 0

Views: 622

Answers (3)

Vaibhav Raut
Vaibhav Raut

Reputation: 472

you can use following solution also

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {

    $scope.parts = [
        {name: "hello", value : 5},
        {name: "Karl", value : 4},
        {name: "Ba", value : 3}

        ];

    $scope.getStyle = function(value)
    {
        var obj = {
            'background-color': 'green',
            'width': parseInt(240/value) + 'px',
            'height': '20px'
        };

        return obj;
    };
}
li .progress_div{
    width: 350px;
    margin-left: 50px;
    display: table-cell;
    margin-left: 150px;
}

li .progress_div .progress_bar{
    border:1px solid black;
    width: 240px;
}
<div ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="part in parts">
            {{part.name}}
         <div class="progress_div">
                <div class="progress_bar">
                    <div ng-style = "getStyle(part.value)"></div>
                </div>
        </div>
            {{part.value}}
        </li>
    </ul>    
</div>

Upvotes: 2

TheRodeo
TheRodeo

Reputation: 465

Another way though I think Pavel's way is better

http://jsfiddle.net/TheRodeo/svy65fa9/

li .progress_div .progress_bar > div.width-3{
    width: 30%;
}
li .progress_div .progress_bar > div.width-4{
    width: 40%;
}
li .progress_div .progress_bar > div.width-5{
    width: 50%;
}

and

<div ng-style="bar_style" class="width-{{part.value}}"></div>

Upvotes: 1

Pavel Kutakov
Pavel Kutakov

Reputation: 971

Simple in-place style calculation:

<div ng-style="{'width': part.value*10+'%'}"></div>

does the trick.

http://jsfiddle.net/15yb42tj/2/

Upvotes: 3

Related Questions