How to handle callback in angularjs?

Problem

I have a registration mechanism in which rootscope variable is send via service. After success it updates the $rootScope.success field. But the angularjs services is callback dependent.The service update the rootscope.success but the function sequentially execute the code.

How do i wait for service to complete its response and then further process?

.controller('RegisterAccountCtrl', function ($scope,$rootScope,registerUser,$location) {

    $rootScope.success = false;
    $scope.registration = $rootScope.registration;

$scope.getEnterGeneratedCode = function(){
        $rootScope.registration = $scope.registration;
        registerUser.registerUser();
        if($rootScope.success){
           $location.path('/confirm');
        }
}

And inside service

.service('registerUser',function($http,$rootScope,$ionicLoading){
    this.registerUser = function(){
        $ionicLoading.show();
        $http({
            method: 'POST',
            datatype:'json',
            data:{obj:$rootScope.registration},
            url: 'http://localhost/LoginService.asmx/CreateUser',
            contentType: "application/json; charset=utf-8",
            cache: false
        }).success(function (data, status, headers, config){
            if (status == '200') {
                var obj = data;
                $rootScope.success = true;
                $ionicLoading.hide();
                //alert(obj);
            }
        }).error(function (data, status, headers, config){
            $ionicLoading.hide();
        });
    };

 return this;
})
Problem courtesy of: Hassaan Khan

Solution

You want to return your $http request from registerUser which can then be used in your controller in the same way you are using it in the service.

Controller:

registerUser.registerUser().success(function(data, status, headers, config){
   //This code will now execute when the $http request has resolved with a success
   if($rootScope.success){
      $location.path('/confirm');
   }
}).error(function(error, status, headers, config){
   //An error occurred in $http request
   console.log(error); 
});

Service:

this.registerUser = function(){
    $ionicLoading.show();
    return $http({
        method: 'POST',
        datatype:'json',
        data:{obj:$rootScope.registration},
        url: 'http://localhost/LoginService.asmx/CreateUser',
        contentType: "application/json; charset=utf-8",
        cache: false
    }).success(function (data, status, headers, config){
        if (status == '200') {
            var obj = data;
            $rootScope.success = true;
            $ionicLoading.hide();
            //alert(obj);
        }
    }).error(function (data, status, headers, config){
        $ionicLoading.hide();
    });
};

A few things worth noting...

You are returning from a service which is not required, a service works as an instance and so the instance is already injected. It is a factory (singleton) that requires a return.

You are setting $scope.registration to be the same as $rootScope.registration and then setting $rootScope.registration to be the same as $scope.registration in your getEnterGeneratedCode function which is unnessasary and should be prototypicaly inherited anyway.

You should always try to defined depedencys with like so:

.controller('RegisterAccountCtrl', ['$scope', '$rootScope', 'registerUser', '$location', function($scope, $rootScope, registerUser, $location){

}]);

Unless $rootScope.success is being used elsewhere its currently pointless to set and I would recommend avoiding setting props on your $rootScope as it can quickly get out of control.

Here is a simplified version of your code:

.controller('RegisterAccountCtrl', [
    '$scope',
    '$rootScope',
    'registerUser',
    '$location',
function($scope, $rootScope, registerUser, $location) {

    $scope.getEnterGeneratedCode = function() {
        $ionicLoading.show();
        registerUser.registerUser().success(function(data, status, headers, config) {
            if (status == '200') {
                var obj = data;
                $ionicLoading.hide();
                $location.path('/confirm');
                //alert(obj);
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
        });

    }

}])

.service('registerUser', [
    '$http',
    '$rootScope',
    '$ionicLoading',
function($http, $rootScope, $ionicLoading) {

    this.registerUser = function() {
        return $http({
            method: 'POST',
            datatype: 'json',
            data: {
                obj: $rootScope.registration
            },
            url: 'http://localhost/LoginService.asmx/CreateUser',
            contentType: "application/json; charset=utf-8",
            cache: false
        });
    };

}]);
Solution courtesy of: Simon Staton

Discussion

Use a promise - see changes below:

.controller('RegisterAccountCtrl', function ($scope,$rootScope,registerUser,$location) {

    $rootScope.success = false;
    $scope.registration = $rootScope.registration;

$scope.getEnterGeneratedCode = function(){
        $rootScope.registration = $scope.registration;
        registerUser.registerUser().then(function() {
          $location.path('/confirm');
        })
}

And inside service

.service('registerUser',function($http,$rootScope,$ionicLoading){
    this.registerUser = function(){
        $ionicLoading.show();
        // Return a promise
        return $http({
            method: 'POST',
            datatype:'json',
            data:{obj:$rootScope.registration},
            url: 'http://localhost/LoginService.asmx/CreateUser',
            contentType: "application/json; charset=utf-8",
            cache: false
        }).success(function (data, status, headers, config){
            if (status == '200') {
                var obj = data;
                // Don't need now - $rootScope.success = true;
                $ionicLoading.hide();
                //alert(obj);
            }
        }).error(function (data, status, headers, config){
            $ionicLoading.hide();
        });
    };

 return this;
})
Discussion courtesy of: Peter Ashwell

This recipe can be found in it's original form on Stack Over Flow.