2016-02-09 17 views
0

在嵌入式的角度控制器內用於在用戶登錄以下兩個片段(來自angular-meteor tutorial截取):JavaScript回調方法不更新AngularJS除非在速記形式

this.login = function() { 
     Meteor.loginWithPassword(this.credentials.email, this.credentials.password, (err) => { 
      if (err) { 
       this.error = err.reason; 
      } 
      else { 
       $state.go('index'); 
      } 
     }); 
    }; 

和:

this.login = function() { 
     Meteor.loginWithPassword(this.credentials.email, this.credentials.password, function(err) { 
      if (err) { 
       this.error = err.reason; 
      } 
      else { 
       $state.go('index'); 
      } 
     }); 
    }; 

首先會導致AngularJS在回調後更新錯誤值,但第二個片段不觸發更新。唯一的區別是在第一個中使用了速記方法聲明。這是什麼原因?

+0

請屁股腳本如何調用這個函數? –

回答

3

這不只是速記,第一個使用arrow function。箭頭函數的處理範圍與function lambda不同。

箭頭函數繼承它們的父範圍。所以,沒有必要在內部綁定this(在這個例子中)。

如果使用function拉姆達,您必須bindthis

this.login = function() { 
     Meteor.loginWithPassword(this.credentials.email, this.credentials.password, function(err) { 
      if (err) { 
       this.error = err.reason; 
      } 
      else { 
       $state.go('index'); 
      } 
     }.bind(this)); 
    };