gpt4 book ai didi

javascript - AngularJS : Not able to access controller's scope variable inside $scope. $上

转载 作者:行者123 更新时间:2023-11-28 18:55:15 24 4
gpt4 key购买 nike

我试图访问 $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'
});
});

关于javascript - AngularJS : Not able to access controller's scope variable inside $scope. $上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33733201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com