2014-09-05 110 views
0

我想知道是否有糖简写为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! 

我想什么做的是这样的:

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! 

绑定参数中的任何方式$scope.arg2$scope.arg3()fnB

+0

你也可以装饰$ q并为其添加一个'.fcall'构造 – 2014-09-06 11:25:39

回答

3

您可以使用function.bind (look at support and shim for older browsers)传递一个绑定的函数引用和您的参数,以在参数调用时将参数绑定到该函数。

someService.fnB.bind(this, $scope.arg2, $scope.arg3); 

你可以通过null作为第一个参数,以及如果你不需要设置一个特定的上下文(你不这样做,它看起来像),如果你需要,你可以通过这方面的第一个论点。

尝试: -

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! 

你也可以使用angular.bind

someService.fnA($scope.arg1) 
    .then(angular.bind(this, someService.fnB, $scope.arg2, $scope.arg3))... 

同样你会发现在你可能已经使用类似Lodash /下划线库类似的方法有bind,jQuery有$.proxy

+0

嗯,这似乎工作;我将使用Lo-Dash的'_.bind'。我只是希望有一个版本不需要'this'。 – user2857125 2014-09-05 19:31:27

+0

@ user2857125是的,你没有提到你正在使用lodash /下划线,很多图书馆都有自己的版本。 jquery有'jquery.proxy'。每个人都需要一个上下文,因为它专门用于创建绑定函数。 – PSL 2014-09-05 19:32:07

+0

@ user2857125看到我的更新角度也有它的一个版本。你也可以使用它。 – PSL 2014-09-05 19:35:43