Reputation: 32758
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?
Upvotes: 0
Views: 74
Reputation: 53
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'...};
Upvotes: 2
Reputation: 42669
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();
});
Upvotes: 1