'this' vs $scope in AngularJS controllers
In the "Create Components" section of AngularJS's homepage, there is this example:
controller: function($scope, $element) {
var panes = $scope.panes = [];
$scope.select = function(pane) {
angular.forEach(panes, function(pane) {
pane.selected = false;
});
pane.selected = true;
}
this.addPane = function(pane) {
if (panes.length == 0) $scope.select(pane);
panes.push(pane);
}
}
Notice how the select
method is added to $scope
, but the addPane
method is added to this
. If I change it to $scope.addPane
, the code breaks.
The documentation says that there in fact is a difference, but it doesn't mention what the difference is:
Previous versions of Angular (pre 1.0 RC) allowed you to use
this
interchangeably with the$scope
method, but this is no longer the case. Inside of methods defined on the scopethis
and$scope
are interchangeable (angular setsthis
to$scope
), but not otherwise inside your controller constructor.
How does this
and $scope
work in AngularJS controllers?