0

我在角初學者,我有角1.5這個簡單的問題美元。我使用rootScope發出一些事件和$ scope。$ on作爲組件控制器中的事件偵聽器(它爲子組件提供數據)。該控制器包含一些複雜的對象,必須通過傳入的事件數據修改該對象。 控制器看起來像這樣(只是舉例):

function ComponentController($scope){ 

    this.abc = 5; 

    $scope.$on('BOOM!', function(events, args){ 
    console.log(args); 
    this.abc = this.abc + args; // example of modifying some controllers data 
    }) 
} 

問題是明確的 - 我不能修改this.abc。那麼,如何訪問控制器數據並在此事件偵聽器中對其進行修改?當我使用$ scope.abc來代替時,它可以工作,但它是否有必要(當我使用無處不在的控制器時)?

回答

0

應該解決您的問題

function ComponentController($scope){ 
    var vm = this; 
    vm.abc = 5; 

    $scope.$on('BOOM!', function(events, args){ 
    console.log(args); 
    vm.abc = vm.abc + args; // example of modifying some controllers data 
    }) 
} 
+1

感謝。有用。問題是在範圍內(事件監聽器有自己的範圍)?我以前沒有想過。 – chobotek

0
function ComponentController($scope){ 
    //Assign this to that, this is in the scope/context of ComponentController. 
    var that = this. 
    that.abc = 5; 

    $scope.$on('BOOM!', function(events, args){ 
    //the this used here earlier was in the scope/context of the function to handle this event 
    // therefore we use the that variable assigned in the ComponentController. 
    console.log(args); 
    that.abc = that.abc + args; // example of modifying some controllers data 
    }) 
}