title: Angular: assign and access promise via rootScope
body: <p>I would like to use a promise and access it through a rootScope instead of using return statement. The problem I am having is that promise is getting resolved before my resolve finishes. In the code below, successFunction in my ajax call is getting executed before my defer.resolve() is completed. Is there anyway I can get my successFunction to wait until after my defer.resolve in app-directive gets completed? Here is my code:</p>
  
  <p>app-directive.js</p>
  
  <pre><code>function(app) {
      app.directive('spinner', function ($uibModal, $timeout, $q) {
      return {
          restrict: 'E',
          replace: true,
          template: [
              '&lt;div style="display:none;" class="modal-dialog"&gt;',
              '&lt;div class="modal-header ng-scope" style="text-align: center;"&gt;',
              '   {{spinnerMessage}}',
              '&lt;/div&gt;',
              '&lt;div class="modal-body ng-scope"&gt;',
              '   &lt;img class="spinner-image" ng-src="../../Content/img/spinner.gif" /&gt;',
              '&lt;/div&gt;',
              '&lt;/div&gt;'
          ].join(''),
          link: function (scope, element) {
              scope.$watch(function () {
                  return scope.$root.loadMask
              }, function () {
                   if (scope.$root.loadMask == true) {
                      scope.spinnerModal = $uibModal.open({
                          template: element[0].innerHTML,
                          size: 'sm',
                          backdrop: 'static',
                          keyboard: 'false'
                      });
                   }
                   else {
                      var defer = $q.defer();
                      $timeout(function () {
                          defer.resolve(scope.spinnerModal.close())
                      }, 3000);
  
                      scope.$root.spinnerClosed = defer.promise;
                   }
              }, true);
  }
  </code></pre>
  
  <p>ajaxService.js</p>
  
  <pre><code>app.register.service('ajaxService', ['$http', '$rootScope', function ($http, $rootScope) {
      this.AddUser = function (user, successFunction, errorFunction) {
          // Initialization
          $rootScope.loadMask = true;
  
          $http.post('Account/AddUser', user)
          .success(function (response, status, headers, config) {
              $rootScope.loadMask = false;
              $rootScope.spinnerClosed.then(function (result) {
                  successFunction(response, status);
              });
          })
          .error(function (response, status) {
              $rootScope.loadMask = false;
              $rootScope.spinnerClosed.then(function (result) {
                  errorFunction(response, status);
              });
          });
      }
  </code></pre>