Johannes
Johannes

Reputation: 2812

Angular Scope Usage

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.

Upvotes: 2

Views: 77

Answers (1)

Nidhish Krishnan
Nidhish Krishnan

Reputation: 20751

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);

Upvotes: 1

Related Questions