[英]How can I access the “this” in my controller when using “the controller as” syntax?
I have the following code: 我有以下代码:
var app = angular.module('plunker', []);
app.controller('ParentCtrl', function($scope) {
$scope.name1 = 'Parent';
this.name1 = 'Parent';
});
app.controller('ChildCtrl', function($scope) {
$scope.name1 = 'Child';
this.name1 = 'Child';
this.option = {};
this.option.abc = 25;
foo = function(){
alert(this.option)
};
foo();
});
When I try to access the "this" before the function it is available. 当我尝试使用该功能之前的“ this”时。 When I try to access the this inside of the function then it's undefined.
当我尝试在函数内部访问this时,它是未定义的。 Can someone tell me is there an "AngularJS" way to resolve this?
有人可以告诉我是否有一种“ AngularJS”方法可以解决此问题?
If you're using Controller As
Syntax then declarations like: 如果您使用
Controller As
Syntax,则声明如下:
$scope.name1 = 'Child';
this.name1 = 'Child';
are redundant. 是多余的。 When you specify the 'As' angular will copy over all properties defined on this, to a $scope variable.
当您指定'As'角时,它将在此定义的所有属性上复制到$ scope变量。
as for why this
doesn't work in your function. 至于为什么
this
在您的功能中不起作用。 The this keyword refers to the executing context of the function. this关键字是指函数的执行上下文。 As you have declared it there is no context.
正如您已经声明的那样,没有上下文。 To get
this
to be what you expect it you can do: 为了得到
this
是你希望它是什么,你可以这样做:
this.foo = function(){...this is this...}
or if you don't wish to expose it on the scope. 或者如果您不想在示波器上显示它。 You can use the module revealing pattern.
您可以使用模块显示模式。
var self = this;
function foo(){...self is 'this'...};
You need to keep the reference of this at the start of the function and use that. 您需要在函数开始时保留对它的引用并使用它。 The context of
this
i believe in your function is the global window. 的情况下
this
我相信在您的函数是全局窗口。 It all depends upon how the function is invoked and where is it defined. 这完全取决于函数的调用方式以及在何处定义。
app.controller('ChildCtrl', function($scope) {
var self=this;
$scope.name1 = 'Child';
this.name1 = 'Child';
this.option = {};
this.option.abc = 25;
foo = function(){
alert(self.option)
};
foo();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.