簡體   English   中英

從AngularJS中的$ scope。$ on訪問控制器范圍

[英]Access to controller scope from $scope.$on in AngularJS

我是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時 ,它可以工作,但是是否有必要(當我在各處使用controllerAs時)?

它應該解決你的問題

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
  })
}
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
  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM