下面是代码。我嵌套了ng-repeat和一个具有所有其他字段总和的字段。
<div class="animate margin-top" >
<div layout="row" layout-align="center" ng-repeat="data in leaderBoardData | orderBy: 'getTotal($index)'" style = "padding: 10px;" class= "md-padding">
<section class="text-center width-20"><a>{{data.handleName}}</a></section>
<section class="text-center width-20" ng-repeat="score in data.score track by $index">{{score}}</section>
<section class="text-center width-20">{{getTotal($index)}}</section>
</div>
</div>
因此,我想根据动态字段
getTotal($index)
对其进行排序。我该怎么办?上面的orderBy无法正常工作。以下是
getTotal()
函数的代码$scope.getTotal = function (index) {
var total = 0
$scope.leaderBoardData[index].score.forEach(function (score) {
total = total + score
})
return total
}
以下是排行榜数据
var leaderBoardData = [ { handleName: 'xyz', score: [1,2,3] },{ handleName: 'acc', score: [4,5,6] } ]
最佳答案
删除orderBy表达式的引号,以便angular知道它是一个函数,您无需显式传递$ index作为参数。
您需要将此{{getTotal($index)}}
更改为{{getTotal(data)}}
,因为此处已经对数据进行了迭代。
因此,基本上:
function Ctrl($scope) {
$scope.leaderBoardData = [{
handleName: 'xyz',
score: [4, 5, 6]
}, {
handleName: 'acc',
score: [1, 2, 3]
}, {
handleName: 'acFc',
score: [1, 2, 4]
}];
$scope.getTotal = function(index) {
var total = 0;
// also change to index as array already passed to function
index.score.forEach(function(score) {
total = total + score;
})
return total;
};
}
<!DOCTYPE html>
<html ng-app>
<head></head>
<body>
<div>
<div ng-controller="Ctrl" class="animate margin-top">
<div layout="row" layout-align="center" ng-repeat="data in leaderBoardData | orderBy: getTotal" style="padding: 10px;" class="md-padding">
<section class="text-center width-20">
<a>{{data.handleName}}</a>
</section>
<section class="text-center width-20" ng-repeat="score in data.score track by $index">{{score}}</section>
<section class="text-center width-20">
<!-- change is here -->
{{getTotal(data)}}
</section>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>
关于javascript - AngularJs动态顺序通过表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31315059/