<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/base/jquery-ui.css">
  <link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">
  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
  
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
  <script src="https://raw.github.com/angular-ui/angular-ui/master/build/angular-ui.js"></script>
  <script src="app.js"></script>
</head>
<body>
  	<div ng-controller="MainCtrl">
  			
		</div>
    <div id="ajaxFailurePopup" style="display: none"></div>
	</body>
</html>
var app = angular.module('plunker', ['ui']);

app.factory('myService', function($http, $q) {

  var service = {};
  
  service.performCall = function($scope){
   $scope.dataFail = false;

   var def = $q.defer();
   var promise = def.promise;
   def.resolve(false);
   
   promise.then(function(data){
      if(data.rootElement){
        //process...
      }else{
        console.log('Setting dataFail to true');
        $scope.dataFail = true;
      }
   });
   
  };
  
  return service;
});

app.controller('MainCtrl', function( myService, $scope) {
  // Call the async method and then do stuff with what is returned inside our own then function
  myService.performCall($scope);
  
  $scope.$watch('dataFail', function(dataFail){
    if(dataFail){
      //open dialog
      $( "#ajaxFailurePopup" ).dialog({
          zIndex: 3003,
          title: "Note:",
          modal:true, // Disable controls on parent page
          buttons: {
              Ok: {
                  text: 'Retry >',
                  "class" : 'ppButton floatRight',
                  click:
                    function() {
                      $scope.$apply(function(){
                        myService.performCall($scope);
                        $("#ajaxFailurePopup").dialog('destroy');
                      });
                       
                     }
                  }
              }
          });
          
      $scope.dataFail = false;
    }
    
  });
  
});