/** * 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); }); }
<!-- Adrián Gómez - http://adgllorente.com --> <div data-ng-app="myApp"> <h3>Results:</h3> <pre data-ng-controller="toBindOrNot"> <p data-ng-repeat="out in output">{{out}}</p> </pre> </div>