var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope, $q, $timeout, $rootScope) {
$scope.accountMoney = 100;
var bankCashCheck = function (cash) {
var cashCheckJob = $q.defer();
var promiseCard = cashCheckJob.promise;
$timeout(function () {
alert("Yes! We got it!");
if ($scope.accountMoney >= cash) {
cashCheckJob.resolve(cash);
} else {
cashCheckJob.reject('No enough money.');
}
}, 5 * 100);
return promiseCard;
};
$scope.getMoney = "N/A";
var companyPromiseCard;
$scope.cash = function (cash) {
companyPromiseCard = bankCashCheck(cash).then(function (getCash) {
$scope.getMoney = getCash;
return 60;
}, function (cancelReason) {
$scope.getMoney = 0;
alert(cancelReason);
return 0;
});
};
$scope.dealMoney = 50;
$scope.buyMachine = function () {
if(companyPromiseCard === undefined){
alert('Not conatct yet!');
return;
}
companyPromiseCard.then(function (money) {
if(money >= $scope.dealMoney){
alert('Get ' + money + '. Give machine.');
}else{
alert('No money, no machine.');
}
});
};
$scope.reset = function () {
companyPromiseCard = undefined;
$scope.getMoney = "N/A";
};
});
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<span>Account money: {{accountMoney}}</span>
<br/>
<span>With $q: I got cash {{getMoney}}</span>
<button ng-click="cash(100)">Cash $100</button>
<button ng-click="cash(150)">Cash $150</button>
<br/><br/>
<span>Machine Deal: {{dealMoney}} </span>
<button ng-click="buyMachine()">Buy Machine</button>
<br/><br/>
<button ng-click="reset()">Reset</button>
</div>
</div>
External resources loaded into this fiddle: