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,746
  • 17
  • 93
  • 178
Johannes
  • 2,732
  • 5
  • 23
  • 32
  • This means your app manipulates controller instances. You can sometimes be passed a controller instance: when using "Controller as" syntax see https://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 Sep 01 '14 at 13:08

1 Answers1

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);
Community
  • 1
  • 1
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
  • Thanks for the comprehensive answer. I will continue using just `$scope` until I really need `this`. – Johannes Sep 01 '14 at 13:29