0

I'm walking through the basics of Angular and know very little about controllers, directives, scope, models etc. In the video, the tutor wrote controllers in this way:

var module = angular.module('name', [dependencies])
                    .controller($scope)...

The only thing I want you to pick from the above snippet is that, he (the tutor) is passing the $scope object to the controller's function. That is fine and that worked.

In an example on official Angular website, I found this code:

angular.module('invoice1', [])
.controller('InvoiceController', function() {
  this.qty = 1;
  this.cost = 2;
  this.inCurr = 'EUR';
  this.currencies = ['USD', 'EUR', 'CNY'];
  this.usdToForeignRates = {
    USD: 1,
    EUR: 0.74,
    CNY: 6.09
  };

I can clearly see that in this example, no $scope is being passed and this is used instead. Does this mean that the $scope passed to a controller function and 'this' inside a controller function are identical objects?

  • Don't forget to look at the Component as well: https://docs.angularjs.org/guide/component. The combination of Components and "Controller as" syntax is very popular nowadays. – Niels Steenbeek May 02 '16 at 11:54

1 Answers1

2

Many different things here.

In the first snippet, you are creating a module with the name "invoice1". This module does not inject any third part library or other modules, therefore the empty [].

After that, you are creating a controller. This controller is injecting the $scope from the Angular library.

In your second snippet, the tutor is using the controllerAs syntax. So you don't need the $scope, but can directly bind your objects to the controller. Inside the view, you can use the name of the controller to refer to the bindings.

<div ng-controller="InvoiceController as invoice">
  {{ invoice.qty }}
</div>
ohboy21
  • 4,259
  • 8
  • 38
  • 66