数组对象的变量到使用 AngularJS 的函数返回的相等值

array object's variable to equal value returned from a function using angularJS

本文关键字:返回 函数 AngularJS 对象 变量 数组      更新时间:2023-09-26

正如您将在几秒钟内看到的那样,我是Angular的新手。 我希望 users 数组中的每个对象都有一个值(差值),这是计算用户分数与最高分数之差的函数返回的结果。* 例如,在我的代码中,哈利的相差为 1。我怎样才能做到这一点?

.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);
            }
        }
    }
})

首先,为了有效地提高,你只想获得一次最高分。

因此,引入一个变量来存储此值,而不是为每个用户一遍又一遍地计算它:

var maxScore = getMaxScore(); // I leave the implementation to you as you seem to know how to do this

其次,使用 JavaScript map 函数,将新属性附加到数组上的每个元素:

users = users.map(function(user) { 
    return user.diff = maxScore - user.score;
});

现在,您有了每个用户带有附加差异属性的用户数组。


如果你只需要在HTML上呈现的差异,另一种更"棱角化"的方法是将maxScore添加到范围中:

$scope.maxScore = getMaxScore();

在 HTML 模板上,将差异作为动态计算值包含在内:

<td>{{maxScore - user.score}}</td>