fortran
fortran

Reputation: 76067

AngularJS promises are not invoking `then` callback when completed

I have something like a master controller that sets some stuff in the scope, so the inner controllers can use it.

That setup work is asynchronous, so I've wrapped it in a promise, but it's not executing it's callback unless it was already resolved (I tried setting a breakpoint, and if I wait enough, it actually runs the then callback).

Here's a fiddle that reproduces my problem with a timeout rather than a network request: http://jsfiddle.net/LMv8v/1/

HTML

<div ng-app>
    <div ng-controller="configController">
        <div ng-controller="testC">
            {{test}}
            {{foo}}
        </div>
    </div>
</div>

Javascript

function configController ($scope, $q) {
    var deferred = $q.defer();
    $scope.config = deferred.promise;

    setTimeout(function() {
        console.log('timeout');
        deferred.resolve({
            'foo' : 'baz'
        });
    }, 1000);
};

function testC($scope) {
    $scope.test = 'I am working, uh?';
    $scope.config.then(function(config) {
        console.log('then...');
        $scope.$apply(function() {
            $scope.foo = config.foo;
        });
    });
};

It shows the 'timeout', but not the 'then...' message.

(I know that this would be better suited for a Service, but I already have plenty of code with the nested scopes and I want to get it working before I start refactoring)

Upvotes: 2

Views: 629

Answers (1)

Mark Coleman
Mark Coleman

Reputation: 40863

If you are using $.getJSON() (from jQuery I am guessing)

You will run into a similar issue where you are resolving something outside of the Angular world, try the following.

$.getJSON('ajax/test.json', function(data) {
   $scope.$apply(function(){
      deferred.resolve({
            'foo' : 'baz'
      });
  });
});

Example on jsfiddle with jQuery ajax

Upvotes: 2

Related Questions