<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.2.21" data-semver="1.2.21" src="https://code.angularjs.org/1.2.21/angular.js"></script>
    <script src="https://msurguy.github.io/ladda-bootstrap/dist/spin.min.js"></script>
    <script src="https://msurguy.github.io/ladda-bootstrap/dist/ladda.min.js"></script>
    <link data-require="bootstrap-css@*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://msurguy.github.io/ladda-bootstrap/dist/ladda-themeless.min.css" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="btnExample">
    
    <div ng-controller="SolutionTwoCtrl">
      <h4>Use custom directive [disableOnPromise], with Ladda loading:</h4>
      
      <button disable-on-promise="refreshTwo()" with-ladda="true" class="btn btn-primary ladda-button" data-style="expand-right">
		    	<span class="ladda-label">Refresh</span>
		  </button>
      
      
      <span>{{ myDataTwo.message }}</span>
    </div>
    
    
  </body>

</html>
var app = angular.module('btnExample', []);

app.controller('SolutionTwoCtrl', function($scope, Data) {
  
  $scope.myDataTwo = {
    message: ''
  };
  
  $scope.refreshTwo = function() {
    $scope.myDataTwo.message = 'refresh in progress';
    
    return Data.refresh().then(
      function(data) {
        $scope.myDataTwo.message = 'Data received, show it now..';
      },
      function(error) {
        $scope.myDataTwo.message = 'Error..';
      });
  };
});


app.factory('Data', function($q, $timeout) {
  return {
    refresh: function() {
      // Simulate an http request:
      var deferred = $q.defer();
      $timeout(function() { deferred.resolve("Good!"); }, 3000);
      return deferred.promise;
		  
      // In real case, something like that:
      // return Restangular.getList('something');
    }
  };
});


app.directive('disableOnPromise', function ($parse) {
    return {
		restrict: 'A',
		compile: function($element, attr) {
			var fn = $parse(attr.disableOnPromise);
			return function clickHandler(scope, element, attrs) {
				var ladda = (attrs.withLadda ? Ladda.create(element[0]) : false);
				
				element.on('click', function(event) {
					attrs.$set('disabled', true);
					if(ladda) ladda.start();
					
					scope.$apply(function() {
						fn(scope, {$event:event}).finally(function() {
							attrs.$set('disabled', false);
							if(ladda) ladda.stop();
						});
					});
				});
			};
		}
	};
});
/* Styles go here */

body {
  margin: 50px;
}