将JavaScript函数的返回值绑定到ng-model

时间:2015-01-09 18:28:50

标签: javascript angularjs

我试图从函数中获取返回值并使用ng-model显示它,但是列为空且日志没有错误。该值应为users数组中的最大分数(最高分:46)。 任何想法为什么不工作?

HTML:

<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 ng-model="maxScore">{{max}}</td>
        </tr>
    </table>
</div>

JS:

var myApp = angular.module("myApp",[]);

myApp.controller ('firstCtrl', function($scope, PersonService){

$scope.users = PersonService.list();
$scope.maxScore = function(users){
    PersonService.getMaxScore(users);
}
})

myApp.service('PersonService',function(){

var uid = 1;
var users = [{
    id: 0,
    'name': 'John',
    'score': 46
},{
    'name': 'Harry',
    'score': 45
},{
    'name': 'Sam',
    'score': 32
}];

this.list = function () {
    return users;
}

this.getMaxScore = function (arr) {
    var max;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].score > (max || 0))
            max = arr[i].score;
    }
    return max;
}
})

1 个答案:

答案 0 :(得分:1)

结帐plnkr

首先你没有打电话给方法。第二,你不是从方法返回。

将您的HTML更改为以下

<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>{{maxScore(users)}}</td>
        </tr>
    </table>
</div>