简体   繁体   中英

angularjs callback / wait for function to finish

I'm i bit stuck with function which is assigned to the $scope variable . need to wait until it's finished.

This is the function assigned to $scope variable :

$scope.ChooseHome = function() {
    ModalWindowService.openChooseHomeDialog($scope);
}

in ModalWindowService I have:

function openChooseHomeDialog($scope) {
    $scope.animationsEnabled = true;

    var modalInstance = $modal.open({
        animation: $scope.animationsEnabled,
        templateUrl: '/view/user/ChooseHomeDialog.html',
        controller: 'chooseHomeDialogController',
        windowClass: 'detail-modal-window'
    });
    modalInstance.result.then(function (CondoID) {
        $scope.choosenCondoID = CondoID;
    });
}

what I want to do is properly receive this variable '$scope.choosenCondoID' after I get it from modal in '$scope.ChooseHome' function and do some work with it.

smth like this options:

$scope.ChooseHome = function() {
    ModalWindowService.openChooseHomeDialog($scope).then(*do my stuff*); /
    ModalWindowService.openChooseHomeDialog($scope).success(*do my stuff*);
}

But it's not working, I'm getting errors like this:

'TypeError: (intermediate value).success is not a function'

Try this:

function openChooseHomeDialog($scope) {
    $scope.animationsEnabled = true;

    return $modal.open({
        animation: $scope.animationsEnabled,
        templateUrl: '/view/user/ChooseHomeDialog.html',
        controller: 'chooseHomeDialogController',
        windowClass: 'detail-modal-window'
    }).result;
}

$scope.ChooseHome = function() {
    ModalWindowService.openChooseHomeDialog($scope).then(*do my stuff*);
}

And...like I commented...passing on the $scope to your service is a bad idea. You should only use $scope in your controller to glue your data to the view. A service just has to do something or return something which you can use.

To complicate it a bit further..you might want to look into the controllerAs syntax as well to be future proof with your code ;)

you must return your promise from openChooseHomeDialog function

...
return modalInstance.result.then(function (CondoID) {
  $scope.choosenCondoID = CondoID;
});

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