angular.js - evalAsync not called

2019-06-12 04:24发布

问题:

on the following jsFiddle i demonstrate a problem that makes me ponder. It stems from the need to send a system wide event to all scopes, telling them that the system has finished bootstrapping. In order to do that, i got the rootScope after bootstrapping, and called its evalAsync. Alas! its not executing.

see here: http://jsfiddle.net/cusrC/8/

angular.element(document).ready(function() {
angular.bootstrap(body, ['app']);
var ngInjector = angular.injector(['ng']);

var rootScope = ngInjector.get('$rootScope');
var x = rootScope.$eval(function(scope) {   
        console.log('in eval');
        scope.$broadcast('onLoad'); 
        scope.$evalAsync(function(scope) {  
            console.log('in evalAsync');
            scope.$broadcast('onLoad'); 
        });
    });
console.log('x',x);
console.log('after');
});

many thanks for any idea or thought Lior

回答1:

Mark is right about calling the $digest function, but there's one more thing: you're not getting the right root scope.

angular.bootstrap returns the injector for the modules, which already pulls in the 'ng' module.

Here's your fiddle, modified.



回答2:

Since your code is running "outside" of Angular, you'll need to call rootScope.$digest() at the end of your sample code to cause a digest cycle to run. Then the expression inside the $evalAsync() will be evaluated/executed.