I am a beginner in AngularJS.
I am working through some code of an expert. I would like to customize the directive and learn something.
The expert always insert:
this.scope = $scope;
in the first line of every controller.
What's the point of this statement, if you later always just use $scope.
-
This means your app manipulates controller instances. You can sometimes be passed a controller instance: when using "Controller as" syntax see docs.angularjs.org/api/ng/directive/ngController (ctrl-as-exmpl). Also, when defining controller for directives. I'm not knowledgeable about the advantages of doing things this way so I'll just leave this as a comment.BiAiB– BiAiB2014年09月01日 13:08:00 +00:00Commented Sep 1, 2014 at 13:08
1 Answer 1
this pointer was referring to $scope instead of the controller.
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.
courtesy of Mark Rajcok taken from How does 'this' and $scope work in AngularJS controllers
without this
app.controller('MyCtrl', function($scope){
$scope.doStuff = function(){
//Really long function body
};
});
with this
var MyCtrl = function($scope){
var _this = this;
$scope.doStuff = function(){
_this.doStuff();
};
};
MyCtrl.prototype.doStuff = function(){
//Really long function body
};
MyCtrl.$inject = ['$scope'];
app.controller('MyCtrl', MyCtrl);
answered Sep 1, 2014 at 13:11
Nidhish Krishnan
20.8k6 gold badges67 silver badges78 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Johannes
Thanks for the comprehensive answer. I will continue using just
$scope until I really need this.Explore related questions
See similar questions with these tags.
lang-js