Should I use `this` or `$scope`?

Both have their uses. First, some history ...

$scope is the "classic" technique while "controller as" is much more recent (as of version 1.2.0 officially though it did appear in unstable pre-releases prior to this).

Both work perfectly well and the only wrong answer is to mix them in the same app without an explicit reason. Frankly, mixing them will work, but it will just add to the confusion. So pick one and roll with it. The most important thing is to be consistent.

Which one? That depends on you. There are many more examples out there of $scope, but "controller as" is picking up steam as well. Is one better than the other? That's debatable. So how do you choose?

Comfort

I prefer the "controller as" because I like hiding the $scope and exposing the members from the controller to the view via an intermediary object. By setting this.*, I can expose just what I want to expose from the controller to the view. You can do that with $scope too, I just prefer to use standard JavaScript for this. In fact, I code it like this:

var vm = this;

vm.title = 'some title';
vm.saveData = function(){ ... } ;

return vm;

This feels cleaner to me and makes it easy to see what is being exposed to the view. Notice I name the variable that I return "vm" , which stands for viewmodel. That's just my convention.

With $scope I can do the same things, so I'm not adding or detracting with the technique.

$scope.title = 'some title';
$scope.saveData = function() { ... };

So its up to you there.

Injection

With $scope I do need to inject $scope into the controller. I don't have to do this with controller as, unless I need it for some other reason (like $broadcast or watches, though I try to avoid watches in the controller).

UPDATE I wrote this post about the 2 choices: http://www.johnpapa.net/do-you-like-your-angular-controllers-with-or-without-sugar/


$scope is being removed in Angular 2.0. Thus, using this would be an approach others want to follow as the date of release of Angular 2.0 comes closer.


My opinion is that 'this' in javascript has enough issues on it's own, and that adding another meaning / use for it not a good idea.

I'd use $scope, for clarity's sake.

UPDATE

There is now the 'controller as' syntax, discussed here. I am not a fan, but now that it's a more 'official' AngularJS construct it deserves some attention.


I think Controller As is better as it allows for more easily nesting scopes as described by Todd Motto here:

http://toddmotto.com/digging-into-angulars-controller-as-syntax/

Also, it will insure that you always have at least one . in your binding expression which forces you to follow the don't bind to primitives recomendation.

Plus you can decouple from the scope which is going away in 2.0.