2014-05-10 57 views
0

如果我有以下代碼。我可以通過使用self變量來訪問函數內部的this,或者有另一種方法可以訪問函數內部的this嗎?沒有使用模塊顯示模式有沒有一種方法可以訪問匿名函數中的「this」?

app.controller('ChildCtrl', function($scope, _o) { 

    var self=this; 
    this.option = {}; 
    this.option.abc = 25; 

    $q.all([_o.getUserProfiles(), 
      _u.getConfigs() 
     ]) 
     .then(function (results) { 
      ???.option.userProfiles = results[0].userProfiles; 
     }); 

回答

5

您可以使用綁定。可能這會對你更舒服。

app.controller('ChildCtrl', function($scope, _o) { 

    this.option = {}; 
    this.option.abc = 25; 

    $q.all([_o.getUserProfiles(), 
      _u.getConfigs() 
     ]) 
     .then(function (results) { 
      this.option.userProfiles = results[0].userProfiles; 
     }.bind(this)); 

更多關於綁定,你可以在這裏閱讀:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

+0

我打開了一個類似的問題:http://stackoverflow.com/questions/23577814/how-can-i-access-我在控制器中使用控制器時,我還可以在那裏使用.bind作爲foo函數嗎? –

+1

這是我使用coffeescript的原因之一:)試試這個:http://coffeescript.org/#fat-arrow –

相關問題