简体   繁体   中英

How to ensure a promise.then(func) has run before in another controller?

I have a Restangular function in controller A that needs to set up a $rootScope variable that is being used in controller B. How can I ensure that the Restangular function is run before controller B is initialized, or is there another way to handle this issue? Thanks.

The usual way to handle dependencies is to use a use a $scope.$watch on the variable you're waiting on and have your other code respond in the callback.

$scope.$watch(function() {
    return $rootScope.resultFromControllerA
}, function(result) {
    if (result) {

        // Configure Controller B
    }
})

Edit, just to add since you suggested it's a promise, just set the promise on the root scope and have your other controller attach to it:

Controller A

$rootScope.controllerASetupPromise = Restangular.get()

Controller B

$scope.$watch(function() {
    return $rootScope.controllerASetupPromise
}, function(thePromise) {
    if (thePromise) {

        thePromise.then(function(response) {

            // Configure Controller B
        });
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM