Use of this
instead of $scope
was not allowed until Angular 1.2 was released. $scope
was the original and this came to essentially supersede it as more often than not they can be used interchangeably. They ARE technically different, though, and it seems you would base a decision to use one over the other on when the function was being called.
From 'this' vs $scope in AngularJS controllers:
this
-
When the controller constructor function is called, this
is the controller.
When a function defined on a $scope
object is called, this
is the "scope in effect when the function was called". This may (or may not!) be the $scope
that the function is defined on. So, inside the function, this
and $scope
may not be the same.
$scope
-
Every controller has an associated $scope object.
A controller (constructor) function is responsible for setting model properties and functions/behavior on its associated $scope
.
Only methods defined on this $scope
object (and parent scope objects, if prototypical inheritance is in play) are accessible from the HTML/view. E.g., from ng-click
, filters, etc.
Clicking the first link will show that this
and $scope
are the same, since "the scope in effect when the function was called" is the scope associated with the ParentCtrl
.
Clicking the second link will reveal this
and $scope
are not the same, since "the scope in effect when the function was called" is the scope associated with the ChildCtrl
. So here, this is set to ChildCtrl
's $scope
. Inside the method, $scope
is still the ParentCtrl
's $scope
.
I try to not use this inside of a function defined on $scope
, as it becomes confusing which $scope
is being affected, especially considering that ng-repeat
, ng-include
, ng-switch
, and directives can all create their own child scopes.