Djave
Djave

Reputation: 9349

Loop up to number in angularjs

I'm sure this is really simple, but I'm only just starting with angular. I have a property.price variable which is either 1, 2 or 3. I wish to display this as £, ££, or £££.

I can display "Price: 2" by going:

Price: {{ price = property.price}}

But I'm getting a bit confused.

<span ng-repeat="n in [] | range:property.price" >£</span>

Upvotes: 2

Views: 1639

Answers (2)

drew_w
drew_w

Reputation: 10430

I created a fiddle that demonstrates what I think you are looking for here (http://jsfiddle.net/gwfPh/72/).

In this I put two variables in scope - amount and repeatCount, which display the amount and the number of times to repeat the pound symbol:

function Main($scope){
    // number of times to repeat
    $scope.repeatCount = 2;
    $scope.amount = 12.15;
}

The rest of this is a filter which appends the specified number of values to the array. In essence when placed in an ng-repeat this will cause the repeater to add that number of extra elements after the repeat has completed. Best of luck!

Upvotes: 2

eddiec
eddiec

Reputation: 7646

You could use the filter mechanic, or you could create your own simple directive. Fiddle - http://jsfiddle.net/2MN5w/1/

<span repeat-by-integer="3">£</span>

myApp.directive('repeatByInteger', function () {
    return {
        link: function (scope, element, attr) {
            var times = parseInt(attr.repeatByInteger) - 1;
            var text = element.html();
            for (var i = 0; i < times; i++) {
                element.append(text);        
            }
        }
    };
});

Upvotes: 0

Related Questions