0

im trying to get returned value from function and display it using ng-model but column is empty and no error on log. the value should be the max score in the users array (highest score :46). any idea why isn't it working?

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
  • Try throwing some console.log() messages throughout the process chain to see where its failing. Commented Jan 9, 2015 at 18:34

1 Answer 1

1

Checkout this plnkr

first you are not calling as method. And second you are not returning from method.

Change your html to following

<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>
Sign up to request clarification or add additional context in comments.

2 Comments

great tip in general but unfortunately still doesn't work after changed to integer
updated my answer. follow the link in answer plnkr.co/edit/MLfaLQzaLBQwlxqmJcj5?p=preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.