hakunamatata
hakunamatata

Reputation: 13

Update value inside angular js function

The controller.js file is given as

function XYZController($rootScope,$scope){
    var vm = this;
    vm.a = 0;
    var change = function(data){
        data.forEach(function(e,i){
            vm.a+=Number(e.value);
        });
    }
    $log.log(vm.a);
}

The function change is called,but the $log.log(a) prints 0,instead of the updated sum.How to take the updated value of vm.a?When I do $scope.$apply,I get an error "$digest is already in progress".

Upvotes: 0

Views: 124

Answers (2)

Dss
Dss

Reputation: 33

You cannot call $log before the completion of your change function else it will return you 0 only.

Upvotes: 0

Martijn Welker
Martijn Welker

Reputation: 5605

You're calling $log.log(vm.a); before calling change(), therefore it logs your vm.a = 0;, if you change your code to this it should work.

function XYZController($rootScope,$scope){
    var vm = this;
    vm.a = 0;
    var change = function(data){
        data.forEach(function(e,i){
            vm.a+=Number(e.value);
        });
        $log.log(vm.a);
    }
}

Upvotes: 2

Related Questions