0

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".

2
  • 1
    How do you call change? Please post all the relevant code. Commented Mar 29, 2016 at 7:01
  • if you are using ng-click, then you don't have to call $apply. Commented Mar 29, 2016 at 7:02

2 Answers 2

2

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

3 Comments

exactly, javascript is synchronous.
The value will be changed, and it will also be usable outside of your function. Why'd you assume that wouldn't be possible ?
Thanks,it changed.I was just wasting time trying to print the updated value,outside the function,without checking if it actually changed.
0

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

Comments

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.