this
reference was pointing towards $scope
rather than the controller itself.
this
- When the constructor function of the controller is invoked, this refers to the controller.
- When a function defined within a $scope object is called, this represents the "scope in effect at the time when
the function was executed". It may or may not be the same as the $scope the function is defined on. **Therefore, inside the function, this and $scope can differ.
$scope
- Each controller has an assigned $scope object.
- A controller (constructor) function is tasked with defining model properties and functions/behavior on its corresponding $scope.
- Only methods declared on this $scope object (and potentially on parent scope objects through prototypical inheritance) are accessible from the HTML/view. For instance, via ng-click, filters, etc.
courtesy of Mark Rajcok extracted from How does 'this' and $scope work in AngularJS controllers
without using this
app.controller('MyCtrl', function($scope){
$scope.doStuff = function(){
//A very lengthy function body
};
});
with using this
var MyCtrl = function($scope){
var _this = this;
$scope.doStuff = function(){
_this.doStuff();
};
};
MyCtrl.prototype.doStuff = function(){
//A very lengthy function body
};
MyCtrl.$inject = ['$scope'];
app.controller('MyCtrl', MyCtrl);