lundi 19 octobre 2015

Why does ng-click on checkbox update the value of array after function is called?

I have an array with persons who have scores. I display with the list of persons with their scores and a checkbox. When the user checks the checkbox, I total all scores that are checked.: http://ift.tt/1Ge7Zlx

However, the totals are one check behind since it seems that when Angular executes the function contained in ng-click, it has not changed updated the value of ng-model.

How can I get Angular to update the value FIRST, and then execute the function?

<div ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="person in persons | orderBy:'score'"><input type="checkbox" ng-model="person.isChecked" ng-click="updateTotals()"/> {{person.name}} = {{person.score}} ({{person.isChecked}}) 

        </li>
    </ul>
    <div>{{message}}</div>
    <div>total score of checked persons: {{total}}</div>
</div> 


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

function MyCtrl($scope, $window) {

    $scope.debug = '';
    $scope.total = 0;

    $scope.persons = [
        {score: 1, name: 'Jim', isChecked: true},
        {score: 2, name: 'Joe', isChecked: false},
        {score: 3, name: 'Angie', isChecked: true}
    ];

    $scope.updateTotals = function() {
        $scope.total = 0;
        for(var x=0; x < $scope.persons.length; x++) {
            var person = $scope.persons[x];
            if(person['isChecked']) {
                $scope.total += person['score'];   
            }
        }
    }

    $scope.updateTotals()
}




Aucun commentaire:

Enregistrer un commentaire