javascript - 使用 "this"语法时如何访问 Controller 中的 "the controller as"?

标签 javascript angularjs

我有以下代码:

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/

相关文章:

javascript - 如何获取当前可见的图 block 坐标?

javascript - Angular $resource get 与 $get

javascript - 使用 AngularJS 进行文件哈希处理

javascript - 使用 AngularJS 的 Flickr 搜索,结果不会让我一直滚动到顶部

html - 使用 AngularJS 显示 json 数组的元素

javascript - iPad 2 和 iPad 3 网站测试

javascript - 链接 JS 翻转图像

javascript - 使用 EmberJS 路由器的绑定(bind)?

javascript - 我需要 'document.ready()' 这段 Javascript 吗?

javascript - AngularJS:在链接方法中添加指令的范围