/**
* Adrián Gómez Llorente
* http://adgllorente.com
*/
angular.module('myApp', [])
.controller('toBindOrNot', toBindOrNotCtrl);
function toBindOrNotCtrl($q, $scope) {
$scope.output = [];
/**
* Obtains a number.
* @return {Promise} To be resolved with a 1.
*/
function giveNumber() {
return $q.when(1);
}
/**
* Sums two numbers.
* @param {number} a First number to sum.
* @param {number} b Second number to sum.
* @return {Promise} to be resolved with the sum of numbers.
*/
function sumTwoNumbers(a, b) {
return $q.when(a + b);
}
// 1. Use an anonymous function as a callback
giveNumber()
.then(function(num) {
return sumTwoNumbers(num, 2);
})
.then(function(result) {
$scope.output.push('Anonymous function: ' + result);
});
// 2. Use bind to chain functions:
giveNumber()
.then(sumTwoNumbers.bind(null, 4))
.then(function(result) {
$scope.output.push('Use bind to chain function: ' + result);
});
// 3. Wrap the function inside another function
function _wrapSumTwoNumbers(num) {
return function(otherNum) {
return sumTwoNumbers(num, otherNum);
}
}
giveNumber()
.then(_wrapSumTwoNumbers(6))
.then(function(result) {
$scope.output.push('Wrap the function in another function: ' + result);
});
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.