17

When I'm updating scope value directly, it updates in view just fine, but when this value is updated from AJAX callback it doesn't update. Here is simplified example - http://jsfiddle.net/hS8Bs/1/

How can I get around it?

Update: I noticed that clicking second time on the link does update the value, but it's not what I'm looking for.

1
  • jsfiddle.net/hS8Bs/3 This is also a possible solution. But the other solution mentioned below which uses a $http is the right way of doing it. Commented Sep 20, 2012 at 14:44

3 Answers 3

43

The real problem is the lack of $scope.$apply. When you are updating the angular model outside of the angular digest you should use apply.

$.getJSON('/echo/json/', {}, function(data){
    $scope.$apply(function(){
        $scope.period = '2010 - 2011';
    });
}); 

This will trigger the diggest to see the update and if your code inside of apply throw an exception it will be redirected to the $exceptionHandler service.

Sign up to request clarification or add additional context in comments.

1 Comment

$scope.$apply is exactly what I have been looking for, thanks!
5

This is an addon to the selected answer, I found that Angular JS still called "Error: $digest already in progress" when I implemented the $apply() function.

So I found Will Vincent's code on this post: AngularJS : What's the Angular way to interact with a form? , it checks for $digest already in progress and only calls $apply() when safe to:

$scope.safeApply = function(fn) {
    var phase = this.$root.$$phase;
    if(phase == '$apply' || phase == '$digest') {
        if(fn && (typeof(fn) === 'function')) {
          fn();
        }
    } else {
       this.$apply(fn);
    }
};

so it would be something like:

$scope.safeApply(function() { ...code here... });

Comments

3

Here is your missing tutorial you need to use $http parameter of controller in order to get field updated. Check your updated example http://jsfiddle.net/hS8Bs/2/

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.