Reputation: 4591
I have an array of objects that all contain a star_rating
property
[{ name: 'Chemistry', star_rating: 3 },
{ name: 'Physics', star_rating: 5 }]
I am displaying these objects in a list via ng-repeat
. What I want to do is display an object's # of stars alongside the maximum # of stars (5)
, so the list will look something like this
Chemistry [*][*][*][ ][ ]
Physics [*][*][*][*][*]
I have an existing solution that calculates and displays this
<i ng-repeat="i in [].constructor(topic.star_rating) track by $index" class="yellow"></i>
<i ng-repeat="i in [].constructor(5 - topic.star_rating) track by $index" class="grey"></i>
This works fine for small arrays, but there is a performance hit when the list grows (UI lags & becomes jittery) as these repeats are multiplied by the # of objects
Is there a more performant solution to my current method?
Thanks for any input!
Upvotes: 0
Views: 58
Reputation: 106
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<style>
.yellow {
color: #ff0000;
}
.grey {
color: #00ff00;
}
</style>
<body>
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.countArr = [0, 1, 2, 3, 4];
$scope.topics = [{ name: 'Chemistry', star_rating: 3 },
{ name: 'Physics', star_rating: 5 }];
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<div ng-repeat="topic in topics">
<span ng-bind="topic.name" ></span> ->
<i ng-repeat="i in countArr" ng-class="{'yellow': $index < topic.star_rating, 'grey': $index >= topic.star_rating}">[<span ng-if="$index < topic.star_rating" >*</span>]</i>
</div>
</div>
</body>
</html>
Upvotes: 2
Reputation: 1867
Create your five options as below. I am showing only two for demonstration purpose.
<div ng-if="topic.star_rating === 1">
<i class="yellow"></i>
<i class="grey"></i>
<i class="grey"></i>
<i class="grey"></i>
<i class="grey"></i>
</div>
<div ng-if="topic.star_rating === 2">
<i class="yellow"></i>
<i class="yellow"></i>
<i class="grey"></i>
<i class="grey"></i>
<i class="grey"></i>
</div>
This should fix your problem.
Upvotes: 1