【发布时间】:2015-03-23 09:37:38
【问题描述】:
我正在尝试在应包含星形图像的 div 上使用 ng-repeat,JSON 中的每个饼图都有一个从 1 到 5 的 rating 属性,我想使用此值循环输出x 星数。我有这个工作,但它的缺陷在于我无法重新排序数组并使星星跟随列表中的正确项目,因为我使用[$index] 来跟踪迭代。
我的解决方案也相当难看,因为我正在创建具有与 rating 属性值一样多的索引占位符的数组,然后将其推入数组以循环出适当数量的图像。我想要一个更优雅的解决方案。
如果不使用[$index],我应该如何解决这个问题?
JSON 片段:
{"pies": [
...
{
"name": "Blueberry pie",
"imageUrl": "img/blueberrypie.png",
"id": "1",
"rating": "5", //Ng-repeat depending on this value
"description": "Blueberry pie is amazing."
},
...
]}
我的控制器:
pieShopApp.controller('shopCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
$scope.pieId = $routeParams.pieId,
$scope.sortingOptions = ['A-Z', 'Rating'],
$scope.sortingValues = ['name', 'rating'],
$scope.ratings = [],
$http.get('jsons/pies.json')
.success(function(data, status) {
$scope.pies = data;
for (i = 0; i < $scope.pies.pies.length; i++) {
switch ($scope.pies.pies[i].rating) {
case "1": $scope.ratings.push(["1"]); break;
case "2": $scope.ratings.push(["1", "2"]); break;
case "3": $scope.ratings.push(["1", "2", "3"]); break;
case "4": $scope.ratings.push(["1", "2", "3", "4"]); break;
case "5": $scope.ratings.push(["1", "2", "3", "4", "5"]); break;
}
}
console.log($scope.ratings);
})
.error(function(status) {
console.log(status);
})
}]);
包含饼图项的列表:
<div id="pie-list-wrapper">
<ul class="nav">
<a href="#/pies/pieid" ng-repeat="pie in pies.pies | filter:query | orderBy:orderProp">
<li class="list-item rounded-corners box-shadow">
<aside>
<img src="{{pie.imageUrl}}" no-repeat alt="Image of the pie">
</aside>
<header>
<h1 ng-bind="pie.name" id="item-name" class="bold-text"></h1>
</header>
<article>
<span ng-bind="pie.description" id="item-desc"></span>
</article>
<footer id="item-rating">
<div ng-repeat="rating in ratings[$index]" class="rating-box"></div> //Contains the stars
</footer>
</li>
</a>
</ul>
</div>
结果:
【问题讨论】:
-
@cyan 已经看了两次,但不知道如何让它在我的情况下工作。
-
$scope.ratings 和 json 数据的填写顺序是一样的吗?对了,能不能把success函数里的代码再做一个代码清洗函数?
-
据我了解,您尝试列出一些数据,而每个数据元素的星级评分从 1 到 5。对吗?
-
是的,看看我添加的图像。
标签: javascript html angularjs ng-repeat