[英]AngularJS : Not able to access controller's scope variable inside $scope.$on
我正在嘗試訪問$scope.$on
作用域變量$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'
});
});
里面的回調$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'
});
});
你應該使用$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);
});
});
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.