Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

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'...};

Solution 2:

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

Post a Comment for "How Can I Access The "this" In My Controller When Using "the Controller As" Syntax?"