2014-09-05 217 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