我尝试从函数获取返回值并使用 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/