2

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.

Alex Man
4,92620 gold badges109 silver badges194 bronze badges
asked Sep 1, 2014 at 12:55
1
  • 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. Commented Sep 1, 2014 at 13:08

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the comprehensive answer. I will continue using just $scope until I really need this.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.