HTML:
<body>
<div ng-controller="firstCtrl">
<table class="table table-hover">
<thead>
<td>Name</td>
<td>Score</td>
<td>Difference</td>
</thead>
<tr ng-repeat="user in users | orderBy: '-score'">
<td >{{user.name}}</td>
<td >{{user.score}}</td>
<td>{{user.difference}}</td>
</tr>
</table>
</div>
</body>
JS:
var myApp = angular.module("myApp",[]);
myApp.controller ('firstCtrl', function($scope, PersonService){
$scope.users = PersonService.list();
$scope.difference = function (id) {
PersonService.difference(id);
}
})
myApp.service('PersonService',function(){
var uid = 1;
var users = [{
id: 0,
'name': 'John',
'score': '46',
'difference': 'diff from top'
},{
id: 0,
'name': 'Harry',
'score': '45',
'difference': 'diff from top'
},{
id: 0,
'name': 'Sam',
'score': '43',
'difference': 'diff from top'
}];
//simply returns the contacts list
this.list = function () {
return users;
}
this.difference = function(id){
for (i in users) {
if (users[i].id == id) {
return (Math.max.apply(Math, users.score) - users[i].score);
}
}
}
})
答案 0 :(得分:0)
首先,为了有效提高,您只想获得一次最高分。
因此,引入一个变量来存储该值,而不是为每个用户反复计算它:
var maxScore = getMaxScore(); // I leave the implementation to you as you seem to know how to do this
其次,使用JavaScript map函数,将new属性附加到数组中的每个元素:
users = users.map(function(user) {
return user.diff = maxScore - user.score;
});
现在,您拥有的users数组为每个用户提供了额外的diff属性。
如果您只需要在HTML上进行演示的差异,那么另一个,更多&#34; Angularish&#34;这样做的方法是将maxScore添加到范围:
$scope.maxScore = getMaxScore();
在HTML模板上,将差异包含为动态计算值:
<td>{{maxScore - user.score}}</td>