0

私はAngularで初心者ですが、Angular 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 
    }) 
} 
関連する問題