Liviu T.
Liviu T.

Reputation: 23664

Purpose of $scope.this property?

UPDATE: angular 1.3.0-rc4 removed $scope.this see commit

Each instance of a $scope has a property named this that points back to itself. Currently (1.2.0rc1) it's not prefixed with $(public/protected) or $$(internal) so it doesn't hint that it's an angular specific property.

What is the use case for it?

Upvotes: 2

Views: 100

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159135

This question had me grepping all through the codebase for an explanation; I finally got a hint from an old test.

Since AngularJS expressions are evaluated in the context of a scope, the scope needs to have a property called this that refers to itself so that expressions that contain this work. Take the following example:

<div ng-controller="FirstController">
  `this.num` (with normal scope): {{this.num}}
</div>

<div ng-controller="SecondController">
  `this.num` (with scope.this removed): {{this.num}}
</div>
app = angular.module('myApp', []);

app.controller('FirstController', function($scope) {
  $scope.num = 10;
});

app.controller('SecondController', function($scope) {
  delete $scope['this'];
  $scope.num = 10;
});

The second example does not work; see http://jsfiddle.net/BinaryMuse/mzbpz/ for a demonstration.

Upvotes: 1

Related Questions