3

In Angular, you can define methods in your controller by attaching them to $scope:

$scope.myFunction = function () { ... }

Of course, you can also attach them to this, which I've seen used for communicating between directives and a parent controller:

/* within the controller */
this.myFunction = function () { ... }

Are there performance differences between the two approaches due to Angular watching the values?

Even if there aren't performance differences, it seems like a nice way of keeping some methods private, so they won't accidentally be accessed from the View.

tereško
  • 58,060
  • 25
  • 98
  • 150
Ben Jacobs
  • 2,526
  • 4
  • 24
  • 34
  • i typically set `$scope` to an object created by a "master" constructor function, containing both private and public vars/properties/methods. then any properties assigned to `this` within the constructor will be accessible by the view, while private variables (created with `var`) will not be. – user428517 Aug 15 '13 at 15:27

1 Answers1

1

From the docs (http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller):

NB: Previous versions of Angular (pre 1.0 RC) allowed you to use this interchangeably with the $scope method, but this is no longer the case. Inside of methods defined on the scope this and $scope are interchangeable (angular sets this to $scope), but not otherwise inside your controller constructor.

So this is $scope, but not for long.

John Tseng
  • 6,262
  • 2
  • 27
  • 35
  • I'm not sure, but for me this 'Are there performance differences between the two approaches due to Angular watching the values?' is not answered? Or it hasn't performance differences? – felipekm Aug 27 '14 at 13:50
  • I think "angular sets this to $scope" means that there are no performance differences. They are the same object. – John Tseng Aug 27 '14 at 13:57
  • 1
    If this and $scope are the same, then using this without injecting $scope will have better performance. No need for injection. – Carlos Calla Sep 26 '16 at 20:19