![](/img/trans.png)
[英]How can I access a scope function in a parent controller from a child controller when using Typescript?
[英]How can I access the “this” in my controller when using “the controller as” syntax?
我有以下代码:
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();
});
当我尝试使用该功能之前的“ this”时。 当我尝试在函数内部访问this时,它是未定义的。 有人可以告诉我是否有一种“ AngularJS”方法可以解决此问题?
如果您使用Controller As
Syntax,则声明如下:
$scope.name1 = 'Child';
this.name1 = 'Child';
是多余的。 当您指定'As'角时,它将在此定义的所有属性上复制到$ scope变量。
至于为什么this
在您的功能中不起作用。 this关键字是指函数的执行上下文。 正如您已经声明的那样,没有上下文。 为了得到this
是你希望它是什么,你可以这样做:
this.foo = function(){...this is this...}
或者如果您不想在示波器上显示它。 您可以使用模块显示模式。
var self = this;
function foo(){...self is 'this'...};
您需要在函数开始时保留对它的引用并使用它。 的情况下this
我相信在您的函数是全局窗口。 这完全取决于函数的调用方式以及在何处定义。
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.