0

I've been reading the ng-book and just worked through the Code School Angular course the other day and am confused about when to use $scope in a controller and when to use an attribute of the controller.

In the code school course, the controllers were setup like this:

app.controller('LibraryController', function(){
  this.books = getBooks //some function that gets an array
});

But in the ng-book and elsewhere, I've only seen this done as a scope:

app.controller('LibraryController', function($scope){
  $scope.books = getBooks //some function that gets an array
})

From what I can tell, these two approaches are exactly the same. The first is used in the view like this:

<div ng-controller="LibraryController as libraryCtrl">
  <ul>
    <li ng-repeat="book in libraryCtrl.books">

While the second would be

<div ng-controller="LibraryController">
  <ul>
    <li ng-repeat="book in books">

Am I not understanding something fundamental here? Is there a difference in these two approaches and why is the $scope approach used almost exclusively?

2 Answers 2

1

I see two reasons why the scope approach is used more than the controller as approach:

  1. The scope approach is the only one that has been existing for a long time. It's only since version 1.2 (IIRC) that the "controller as" syntax was introduced. Most people got used to the traditional way, most example were written that way.
  2. The handling of this in JavaScript is a nightmare (IMHO). You have to read the documentation of ever callback function used to make sure that this doesn't change when the callback is called. Using the scope doesn't have this problem.
Sign up to request clarification or add additional context in comments.

1 Comment

this is their official reasoning for the difference in the tut. Seems like just a way to isolate things when teaching: help.codeschool.com/discussions/shaping-up-with-angularjs/…
1

It's better to use $scope because you are within the context of a Controller and it makes no sense to address it explicitly on each reference to a scope attribute

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.