Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

AngularJS controller this.model vs $scope.model

I have just finished most of the AngularJS module here on Teamtreehouse. I had previously walked through another AngularJS course offered at:

https://www.codeschool.com/courses/shaping-up-with-angular-js

In the above course $scope is never talked about. I am guessing because it's more of a basic class. Gregg Pollack the course instructor however uses the javascript keyword "this" to attached models to the controller. How is this different from using $scope. What are the advantages/disadvantages of using $scope?

1 Answer

Sean T. Unwin
Sean T. Unwin
28,690 Points

On the surface, in the context of Controllers, the two are interchangeable. Underneath, however, pushing everything into $scope is not always necessary while adding unneeded bloat to $scope. You are, of course, free to use whichever method is most comfortable to you, though.

Think of Controllers as Classes, especially when taking advantage of the "Controller as" syntax. One purpose of a class is for isolation and Controllers are no different, so with that in mind it makes sense to limit which properties and/or methods are exposed to $scope, then explicitly passing them to $scope as needed.

It is considered a good practice to encapsulate this to the controller with a variable to avoid conflict through confusion of this,

e.g

function myCtrl() {
  var _this = this;
  _this.prop = 'someValue';
}

Whichever name you use for this should be consistent. In a popular Angular style guide, John Papa suggests using var vm = this where vm stands for 'ViewModel'. His style guide, in this respect, is influenced by Todd Motto's style guide. I highly recommend checking out both.

You are encouraged to, and should when required, to pass in $scope to the controller when you need to access one or more methods of $scope such as $watch, $digest, $emit, etc. Although, bind only what is needed to $scope.


Other resources: