javascript - 将 JavaScript 函数的返回值绑定(bind)到 ng-model

标签 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;
}
})

最佳答案

看看这个 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>

关于javascript - 将 JavaScript 函数的返回值绑定(bind)到 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27866904/

相关文章:

javascript - 如何使用 jqxListbox 将项目添加到组中

javascript - 页面加载后表单提交按钮无法立即工作

javascript - 使用 JavaScript 和 Angularjs 返回正确名称大小写的函数?

javascript - 如何动态显示图像横向和纵向

javascript - Facebook 共享无法正常工作(使用直接 uri)

javascript - 使用 jQuery 获取表格行值

php - JQuery 图像叠加(并摆脱 imagecopymerge)

javascript - 启动重新初始化 jquery 脚本后 Angular 停止工作

javascript - 为什么我的指令被调用两次?

javascript - Angular Material md-contact-chips 回调问题