1

I'm doing an online course on AngularJS and they suggest to write controllers like this:

Controller:

app.controller("TestController", function() {
    this.printable = "Hello, World";
});

View:

<div ng-controller="TestController as test">
    <h1>{{ test.printable }}</h1>
</div>

Which is odd, as every other tutorial I've read suggests to write the controller as:

app.controller("TestController", ["$scope", function($scope) {
    $scope.printable = "Hello, World";
});

What's the difference between the two approaches?

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176

1 Answers1

1

The difference is the scope of the object you're interacting with. $scope is an object injected into your controller. Your controller is an object representative of a given piece of your angular application.

Earlier on in Angular, controllers weren't objects. They are now.

You should be fine going either way (if you're concerned about which is correct), but controller as is a little more concise.

J.Wells
  • 1,749
  • 12
  • 13