2016-05-15 12 views
-1

目前我的控制器如下所示。我必須創建一個新變量parent來存儲控制器的上下文,以便我可以在登錄函數返回的許諾內使用它。登錄功能在另一個服務中。Angularjs在promise中使用「this」關鍵字回電

是否有使用this關鍵字來引用響應對象而不是使用變量並在其中存儲當前上下文?登錄功能是通過ng-click事件調用的。

function loginCtrl(Service, $state) { 
    this.emailAddress =null; 
    this.password = null; 
    var parent = this; 
    parent.response = common.getNewResponseObject(); 

    this.login = function() { 
     Service.login(this.emailAddress, this.password) 
     .success(success) 
     .error(error); 
    } 

    function error(data) { 
     parent.response.errorResponse = { errors: [{ message: data.error_description }] } 
    } 

    function success(data) { 
     authService.setAuthData(data); 
     $state.go(common.states.dashboard); 
    } 
} 

angular 
    .module('app') 
    .controller('loginCtrl', ['Service', '$state', loginCtrl]) 
+0

將vm附加到此使用Var vm =此 –

+0

,沒有任何區別。我希望能夠在promise回調中做到這一點。 – joe

+0

開始時賦值變量,不要再次使用'this'來保持一致性。請參閱[約翰爸爸角度風格指南](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y032) – charlietfl

回答

0

是的,可以在函數中調用bind方法,並傳入的這個值「注入」的this封閉塊的值。

例如。

var error = (function (data) { 
    this.response.errorResponse = { errors: [{ message: data.error_description }] } 
}).bind(this); 

但是我不確定你爲什麼不把它設置爲this.error,所以你不必調用bind。