AngularJS:无法在$ scope。$ on中访问控制器的范围变量

时间:2015-11-16 10:32:46

标签: javascript angularjs angularjs-scope

我正在尝试访问$scope.$on内的范围变量,但它返回undefined,但是如果我使用普通变量,它工作正常。

Example: 

app.controller('myCtrl',function($scope){
 this.a = "hello";
 var b = "hi";
 // some code

 $scope.$on('someEvent',function(scope,ele,attrs){
  console.log(this.a); // prints 'undefined'
  console.log(b);  //prints 'hi'
 });
});

2 个答案:

答案 0 :(得分:2)

$on的回调中,this的值将是该回调。由于您未在该回调中定义名称为a的任何媒体资源,因此它将为undefined

app.controller('myCtrl',function($scope){
 this.a = "hello";
 var b = "hi";
 // some code
 var that = this; // <<<<<<<<< 
 $scope.$on('someEvent',function(scope,ele,attrs){
  console.log(that.a); // prints hello
  console.log(b);  //prints 'hi'
 });
});

答案 1 :(得分:1)

您应该使用$scope.a代替this.a。另外,b也被错误使用。

您的代码应如下所示:

app.controller('myCtrl',function($scope){
 $scope.a = "hello";
 $scope.b = "hi";
 // some code

 $scope.$on('someEvent',function(scope,ele,attrs){
  console.log($scope.a); 
  console.log($scope.b); 
 });
});
希望有所帮助。