简体   繁体   中英

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. 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?

If you're using Controller As Syntax then declarations like:

$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 for why this doesn't work in your function. The this keyword refers to the executing context of the function. As you have declared it there is no context. To get this to be what you expect it you can do:

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. 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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM