Reputation: 226
I was wondering if there is a sugar shorthand for the following in AngularJS:
$scope.parseSomeString = function (str) {
console.log(str);
// ...
};
someService.fnA($scope.arg1) // fnA doesn't return anything
.then(function () {
return someService.fnB($scope.arg2, $scope.arg3()) // fnB returns some, e.g. string
})
.then($scope.parseSomeString); // this shorthand is great!
What I would like to do is something like this:
someService.fnA($scope.arg1)
.then(someService.fnB($scope.arg2, $scope.arg3())) // but of course, this just calls the function; not good
.then($scope.parseSomeString); // this shorthand is great!
Any way to bind the arguments $scope.arg2
and $scope.arg3()
to fnB
?
Upvotes: 0
Views: 945
Reputation: 123739
You could pass in a bound function reference with your arguments using function.bind (look at support and shim for older browsers) to bind the arguments to the function when it is invoked.
someService.fnB.bind(this, $scope.arg2, $scope.arg3);
You could pass null
as the first argument as well if you don't need to set a specific context(which you don't, it looks like), if you need you can pass that context as the first argument.
Try:-
someService.fnA($scope.arg1)
.then(someService.fnB.bind(this, $scope.arg2, $scope.arg3)) // but of course, this just calls the function; not good
.then($scope.parseSomeString); // this shorthand is great!
You could also use angular.bind
someService.fnA($scope.arg1)
.then(angular.bind(this, someService.fnB, $scope.arg2, $scope.arg3))...
Similarly you will find similar methods in the libraries you may already been using like Lodash/underscore has bind, jquery has $.proxy etc..
Upvotes: 3