2014-09-05 5 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' 구조를 추가 할 수도 있습니다. –

답변

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! 

당신은 또한 마찬가지로 당신이 이미 Lodash/밑줄처럼 사용하고 있습니다 라이브러리에서 유사한 방법을 찾을 수 angular.bind

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

를 사용할 수는 bind을 가지고, JQuery와는 $.proxy있다

+0

흠. 나는 Lo-Dash의'_.bind'를 사용할 것입니다. 나는 단지 '이'가 필요없는 버전이 있었으면 좋겠다. – user2857125

+0

@ user2857125 그래, 당신은 당신이 로다시/밑줄을 사용하고 있다고 언급하지 않았다. 예 많은 도서관은 그것의 자신의 버전을 가지고있다. jquery에는'jquery.proxy'가 있습니다. 바인딩 된 함수를 만드는 데 특히 사용되기 때문에 모든 사람이 컨텍스트를 사용합니다. – PSL

+0

@ user2857125 내 업데이트보기 각도 또한 하나의 버전이 있습니다. 당신도 그것을 사용할 수 있습니다. – PSL

관련 문제