我有以下代码:
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
语法,则声明如下:
$scope.name1 = 'Child';
this.name1 = 'Child';
是多余的。当您指定“As” Angular 时,会将在此定义的所有属性复制到 $scope 变量。
至于为什么this
在你的函数中不起作用。 this 关键字指的是函数的执行上下文。正如您所声明的那样,没有上下文。要使 this
达到您的预期,您可以执行以下操作:
this.foo = function(){...this is this...}
或者如果您不想将其暴露在示波器上。您可以使用模块显示模式。
var self = this;
function foo(){...self is 'this'...};
关于javascript - 使用 "this"语法时如何访问 Controller 中的 "the controller as"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23577814/