我怎样才能访问"本"在我的控制器使用&QUOT时,控制器为"句法? [英] How can I access the "this" in my controller when using "the controller as" syntax?

查看:136
本文介绍了我怎样才能访问"本"在我的控制器使用&QUOT时,控制器为"句法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的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();
});

当我尝试访问这个功能之前,它是可用。当我尝试访问该函数的这里面那么它的定义。谁能告诉我,有一个AngularJS的方式来解决这个问题?

When I try to access the "this" before the function it is available. When I try to access the this inside of the function then it's undefined. Can someone tell me is there an "AngularJS" way to resolve 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. 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();
});

这篇关于我怎样才能访问"本"在我的控制器使用&QUOT时,控制器为"句法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆