lvarayut
lvarayut

Reputation: 15349

How to use a variable inside the ng-repeat?

I'm using the ng-repeat to list all the products, and I want to print out a star symbol x times depending on the product.rating. So, the code looks like following:

<p class="bs-rating"><i class="fa fa-star" ng-repeat="i in getRating({{ product.rating }}) track by $index"></i></p> 

However, it parsed the product.rating as a String: Error: [$parse:syntax] http://errors.angularjs.org/1.3.0-beta.8/$parse/syntax?p0=product.rating&p1=is

I have tried to remove the curly brackets, {{ }}:

<p class="bs-rating"><i class="fa fa-star" ng-repeat="i in getRating(product.rating) track by $index"></i></p> 

It gave me undefined. My getRating() is declared as following:

$scope.getRating = function(rating){
    return new Array(parseInt(rating));
}

Could you help me figure it out how to pass a variable to ng tag?

Upvotes: 0

Views: 1026

Answers (1)

Cipto HD
Cipto HD

Reputation: 704

The problem is on getRating function ie on generating the array. I have developed an alternative solution on this link rating using ng-repeat @jsfiddle

<div ng-app="myApp" ng-controller="myCtrl">
<ol>
    <li ng-repeat="product in products">
        {{product.name}} 
        (
        <span style="font-weight:bold" ng-repeat="i in
           getRating(product.rating)">
            x
        </span>
        )
    </li>
</ol>

var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope){
    $scope.products = [
        {name : "product1", rating:3},
        {name : "product2", rating:5},
        {name : "product3", rating:1}
        ];
    $scope.getRating = function(rating){
        var ratingArray = [];
        for (var i = 1; i <= rating; i++) {
            ratingArray.push(i);
        }
        return ratingArray;
    };
});

Hopefully it will help. Cheers

Upvotes: 1

Related Questions