0

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?

3
  • what version of angular are you using? Commented May 10, 2014 at 6:27
  • I am using the latest 1.2.16 Commented May 10, 2014 at 6:39
  • you can set the context of the foo function foo.call(this);. Usually the context in functions will be window or null if you are using strict mode. Commented May 10, 2014 at 7:02

2 Answers 2

2

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'...};
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Thanks. It works good. Do you think it would be a good idea for me to all use self when setting variables outside the function. For example self.name1 = 'Child' etc. ?
You can assign variable using this. The problem is with the function invocation. Depending on how the function is invoked the context of this changes. If you had defined function this.foo=function() and then called this.foo(), things would work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.